每日刷题 day09---二叉树的深度

81 阅读1分钟

111. 二叉树的深度 - 力扣(LeetCode) (leetcode-cn.com))

image.png

思路1:这题就是,当节点为空时,返回

当root.left ==null && root.right !=null return 1+ 函数(root.right) 当root.left !=null && root.right ==null return 1+ 函数(root.left)

最后 return Math.min(minDepth(root.left),minDepth(root.right))+1

var minDepth = function(root) {
    if(!root) {
        return 0
    }
    if(root.left == null && root.right != null){
        return 1+minDepth(root.right)
    }

    if(root.left != null && root.right == null){
        return 1+minDepth(root.left)
    }
    return Math.min(minDepth(root.left),minDepth(root.right))+1

};

思路2:首先初始化一个最小值是10000,然后扫描整棵二叉树。当二叉树为叶子节点的时候,更新最小值,当有左节点或者有节点的时候,调用函数,深度加1

var minDepth = function(root) {
    if(!root) {
        return 0
    }
    let res = 10000

    function findMIn(root,d){
        if(root.left == null && root.right == null){
            res = Math.min(res,d)
            return
         }
         if(root.left != null){
              findMIn(root.left,d+1)
         }
         if(root.right != null){
              findMIn(root.right,d+1)
         }
    }
    findMIn(root,1)
    return res
};

此外,也有求二叉树最大深度的,和最小深度解题思路一样,这里直接放代码了

思路一

var maxDepth = function(root) {
    if(!root) return 0
    return 1 + Math.max(maxDepth(root.left),maxDepth(root.right))

};

思路二

var maxDepth = function(root) {
    if(!root) return 0
    let res = 0
    function findMax(root,d){
        if(root.left == null && root.right == null){
            res = Math.max(res,d)
            return
        }
        if(root.left != null){
            findMax(root.left,d+1)
        }
        if(root.right != null){
            findMax(root.right,d+1)
        }
    }
    findMax(root,1)
    return res

};