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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
return its depth = 3
**大意:**二叉树的最大深度.
实现:
方法一:层序遍历实现即可,设置一个count,每遍历一层count++。
方法二:递归 终止条件(root==NULL)
否则max(左子树深度,右子树深度)+1;(因为树从0开始,所以要+1)
方法一:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
int count = 0;
std::queue<TreeNode *> q;
q.push(root);
while(!q.empty()){
int n = q.size();
for(int i = 0;i < n;++i){
TreeNode *node = q.front();
if(node->left != NULL)
q.push(node->left);
if(node->right != NULL)
q.push(node->right);
q.pop();
}
count++;
}
return count;
}
};
方法二:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};