Maximum Depth Of Binary Tree 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
输入:
[3,9,20,null,null,15,7],
输出:
3
返回它的最大深度 3
方法一:递归
二叉树的最大深度即为1+左右子树的最大深度
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
方法二:层次遍历
二叉树的层次遍历,记录遍历的层数
class Solution {
public:
int maxDepth(TreeNode* root) {
int res=0;
if(!root)return res;
queue<TreeNode*>q{{root}};
while(!q.empty()){
for (int i = q.size()-1; i >= 0; i--) {
auto temp=q.front();q.pop();
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);
}
res++;
}
return res;
}
};