leetcode-Easy-31-Tree- Maximum Depth of Binary Tree

题目:找出二叉树的最大深度

Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.

  • Example 1
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
return its depth = 3.



  • 解法1-递归
var maxDepth = function(root) {
    if(!root) return 0
    return 1 + Math.max(maxDepth(root.left),maxDepth(root.right))
};

  • 解法2-BST
function maxDepth(root){
    if(!root) return 0;
    let queue = [root]
    let depth = 0 // 为什么取0不是1,区别二叉树最小深度
    while(queue.length){
        let len = queue.length
        // while (len--) {
        for(let i = 0; i < len; i++){
            let node = queue.shift()
            if(node.left) queue.push(node.left)
            if(node.right) queue.push(node.right)
        }
        depth++
    }
    return depth
}

  • 二叉树最小深度
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
}



你可能感兴趣的:(leetcode-Easy-31-Tree- Maximum Depth of Binary Tree)