Given a binary tree,find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
此题是经典的求二叉树深度深度题目,可采用递归的方式,以此求每个节点的左子树深度和右子树深度,然后返回该节点左右子树深度最大的那个即为该节点的深度
具体代码如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
if(root == NULL)
return ; int nleft = maxDepth(root->left);
int nright = maxDepth(root->right); return (nleft > nright) ? (nleft+) : (nright+);
}
};