力扣:二叉树的最大深度js

5,152 阅读1分钟

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

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

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

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/ma…

解题思路;

要找到最深的深度,用递归调用maxDepth方法就可以搞定,接下来就是处理时间复杂度和空间的问题,当root为 null时,肯定长度为0

var maxDepth = function(root) {
    if(!root){return 0}
    else{
        let left=maxDepth(root.left);
        let right=maxDepth(root.right);
        return ((left>right)?left:right)+1
    }
};


题目二:二叉树的最小深度

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

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

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

示例:

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最小深度  2.

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/mi…

解题思路:

当root不存在时,返回0,当左右节点不存在时,返回1,当右叶节点不存在时,则此时最短为左叶节点,当左叶节点不存在时,则此时最短为右叶节点,当左右节点都存在时,比较左右节点的值,返回小的值

var minDepth = function(root) {
    if(!root){
        return 0
    }
    if(root.right==null&&root.left==null){
        return 1
    }
    if (root.left&&!root.right){
        return 1+minDepth(root.left);
    }
    if (!root.left&&root.right){
        return 1+minDepth(root.right);
    }
    return 1+Math.min(minDepth(root.left),minDepth(root.right)) //存在两个字节点

};