104.二叉树的最大深度

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

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

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

示例:

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度  3

解法

方法一:递归

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function (root) {
  return root ? Math.max(maxDepth(root.left), maxDepth(root.right)) + 1 : 0;
};

方法二: BFS

广度优先算法,首先遍历第一层,然后遍历第 2 层,然后遍历第 3 层。

内层循环 获取的是 length,而不是 queue.length,这个 length 指的是这一层级元素的个数,比如第一层一个 root 元素,第二层两个,第三层四个,弟第四层八个...

在遍历当前层的时候同样会收集下一层的节点,在下一轮外层循环的时候(当前内层循环完成后)获取 length 进行遍历

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function (root) {
  if (root == null) {
    return 0;
  }
  const queue = [];
  let level = 0;

  queue.push(root);

  while (queue.length) {
    let length = queue.length;
    while (length-- > 0) {
      const current = queue.shift();

      if (current.left !== null) {
        queue.push(current.left);
      }
      if (current.right !== null) {
        queue.push(current.right);
      }
    }
    level++;
  }
  return level;
};

方法二:DFS

深度优先算法

使用两个栈,一个记录节点的stack栈,一个记录节点所在层数的level栈,stack中每个节点在level中都会有一个对应的值,并且他们是同时出栈,同时入栈

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function (root) {
  if (root === null) {
    return 0;
  }
  const stack = [];
  const levelStack = [];
  let max = 0;
  stack.push(root);
  levelStack.push(1);
  while (stack.length) {
    const temp = stack.pop();
    const level = levelStack.pop();
    max = Math.max(level, max);
    if (temp.left !== null) {
      stack.push(temp.left);
      levelStack.push(level + 1);
    }
    if (temp.right !== null) {
      stack.push(temp.right);
      levelStack.push(level + 1);
    }
  }
  return max;
};