目录
问题描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
实现代码:
递归:
class Solution {
public:
int maxDepth(TreeNode* root)
{
if(root==NULL)
{
return 0;
}
int a=maxDepth(root->left);//左子树深度
int b=maxDepth(root->right);//右子树深度
return a>b?(a+1):(b+1);//左子树深则返回左子树加一,反之返回右子树加一
}
};
可精简成:
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
层序遍历:
class Solution {
public:
int maxDepth(TreeNode* root)
{
if(root==NULL)
{
return 0;
}
queue<TreeNode*> que;
que.push(root);
int result=0;
while(!que.empty())
{
result++;//每进入一层则加一
int size=que.size();
while(size--)
{
TreeNode* temp=que.front();
que.pop();
if(temp->left) que.push(temp->left);
if(temp->right) que.push(temp->right);
}
}
return result;
}
};
原理思路:
比较简单就不详写解释了。
递归就是判断左右子树谁深就加一返回到上一层。
层次遍历就是基础的层次遍历,每进入一层就让深度加一即可。