leetcode104-二叉树的最大深度

原题

给定一个二叉树,找出其最大深度。

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

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

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

解法

思想

  1. 自底向上,每个节点是左右两个孩子节点的深度的最大值+1
  2. 自顶向下,依次更新最大高度

代码

自底向上:

class Solution {
    public int maxDepth(TreeNode root) {
        return depth(root);
    }
    public int depth(TreeNode root){
        if(root == null) return 0;
        if(root.left == null && root.right == null) return 1;
        return Math.max(depth(root.left),depth(root.right))+1;
    }
}

自顶向下:

class Solution {
    int depth = 0;
    public int maxDepth(TreeNode root) {
        depth(root,1);
        return depth;
    }
    public void depth(TreeNode root,int cur){
        if(root == null) return;
        if(cur>depth) depth = cur;
        depth(root.left,cur+1);
        depth(root.right,cur+1);
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode104-%e4%ba%8c%e5%8f%89%e6%a0%91%e7%9a%84%e6%9c%80%e5%a4%a7%e6%b7%b1%e5%ba%a6/

发表回复

登录后才能评论