Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二叉树的最大深度-104 #53

Open
sl1673495 opened this issue Jun 5, 2020 · 0 comments
Open

二叉树的最大深度-104 #53

sl1673495 opened this issue Jun 5, 2020 · 0 comments
Labels
BFS 广度优先遍历 DFS 深度优先遍历 二叉树

Comments

@sl1673495
Copy link
Owner

sl1673495 commented Jun 5, 2020

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 sl1673495 added DFS 深度优先遍历 二叉树 BFS 广度优先遍历 labels Jun 5, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
BFS 广度优先遍历 DFS 深度优先遍历 二叉树
Projects
None yet
Development

No branches or pull requests

1 participant