给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶节点的最长路径上的节点数。
案例:
给出二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回最大深度为 3 。
详见:https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
方法一:非递归
/**
* Definition for a binary tree node.
* 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)
{
return 0;
}
queue<TreeNode*> que;
que.push(root);
int i=1;
int depth=0;
while(!que.empty())
{
root=que.front();
que.pop();
--i;
if(root->left)
{
que.push(root->left);
}
if(root->right)
{
que.push(root->right);
}
if(i==0)
{
i=que.size();
++depth;
}
}
return depth;
}
};
方法二:递归
/**
* Definition for a binary tree node.
* 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)
{
return 0;
}
int left=maxDepth(root->left);
int right=maxDepth(root->right);
return max(left,right)+1;
}
};