您的位置:首页 > 其它

LeetCode 104 二叉树的最大深度

2019-03-04 10:14 288 查看
  • 题目:
    给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

返回它的最大深度 3 。

  • 解题思路:
    1.自顶向下递归:
    代码实现:
int res = 0;
int maxDepth(TreeNode* root) {
if(!root) return res;
int depth = 1;
max1(root, depth);
return res;
}
void max1(TreeNode* root, int depth)
{
if(!root) return ;
res = max(res,depth);
max1(root->left, depth+1);
max1(root->right, depth+1);
}

2.自下向上
代码实现:

int maxDepth(TreeNode* root) {
if(!root) return 0;
int max1 = maxDepth(root->left);
int max2 = maxDepth(root->right);
return max1 > max2? max1+1: max2+1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐