leetcode-javascript icon indicating copy to clipboard operation
leetcode-javascript copied to clipboard

二叉树的最大深度-104

Open sl1673495 opened this issue 4 years ago • 0 comments

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

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

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

示例:

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

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

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree

思路

DFS

简单的 DFS 思路就是递归的遍历整个子树,每递归一个子节点就把传入的 depth 参数 +1,并且去对比全局保存的最大值变量 max 并且更新。

let maxDepth = function (root) {
  let max = 0
  let helper = (node, depth) => {
    if (!node) return
    max = Math.max(max, depth)
    if (node.left) {
      helper(node.left, depth + 1)
    }
    if (node.right) {
      helper(node.right, depth + 1)
    }
  }
  helper(root, 1)
  return max
}

BFS

BFS 的思路还是套标准模板,每次循环是一层的分界点,在每轮循环中不停的把下一层的子节点加入到队列中,下次循环则继续处理这些子节点,并且每轮循环都把 max + 1,这样最后的 max 就是最大的深度了。

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
let maxDepth = function (root) {
  if (!root) return 0
  let max = 0
  let queue = [root]

  while (queue.length) {
    max += 1
    let len = queue.length
    while (len--) {
      let node = queue.shift()
      if (node.left) {
        queue.push(node.left)
      }
      if (node.right) {
        queue.push(node.right)
      }
    }
  }

  return max
}

bobo 老师的解法

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

sl1673495 avatar Jun 05 '20 02:06 sl1673495