leetcode-tree-111- Minimum Depth of Binary Tree

题目:Balanced Binary Tree

Minimum Depth of Binary Tree

  • Example 1
    Given the following tree [3,9,20,null,null,15,7]:
    3
   / \
  9  20
    /  \
   15   7

minimum depth = 2

解法1-递归

function minimumDepth(root){
    if(!root) return 0;
    if(!root.left) return 1 + minimumDepth(root.right)
    if(!root.right) return 1 + minimumDepth(root.left)
    return 1+ Math.min(minimumDepth(root.left,root.right))
}

解法2-BST

function minDepth(root){
    if(!root)  return 0;
    let queue = [root]
    let depth = 1; // 为什么取1 不是0,因为下面根节点如果没有左右节点,他还是为1
    while(queue.length){
        let len = queue.length;
        for(let i = 0; i < len; i++){ // 保证每一层遍历完以后,在继续往下遍历判断
            let node = queue.shift()
            if(!node.left && !node.right) return depth
            if(node.left)  queue.push(node.left)
            if(node.right) queue.push(node.right)
        }
        depth++
    }
    return depth
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容