Skip to content

面试题55 - I. 二叉树的深度

示例

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

    3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3 。

JS

1.递归思路

js
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
const maxDepth = function (root) {
  const treeDep = function (node, n = 0) {
    if (node) {
      const l = treeDep(node.left, n + 1)
      const r = treeDep(node.right, n + 1)
      return l > r ? l : r
    }
    return n
  }
  return treeDep(root)
}

2.非递归思路 使用层序遍历(BFS)

js
/**
 * @param {TreeNode} root
 * @return {number}
 */
const maxDepth = function (root) {
  const treeDep = function (node) {
    let level = 0
    const queue = []
    if (!node) {
      return level
    }
    queue.push(node)
    while (queue.length !== 0) {
      let len = queue.length
      level++
      while (len) {
        const n = queue.shift()
        if (n.left) {
          queue.push(n.left)
        }
        if (n.right) {
          queue.push(n.right)
        }
        len--
      }
    }
    return level
  }
  return treeDep(root)
}

题链