LeetCode-104. Maximum Depth of Binary Tree

问题描述

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -100 <= Node.val <= 100

解答

方法一:递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*
* @Description: 104. Maximum Depth of Binary Tree
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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)
* }
*/
/**
* @description: 递归解法
* @param {TreeNode} root
* @return {number}
*/
const maxDepth = function (root) {
if (!root) {
return 0
}

return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
}
方法二:层序遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
* @Description: 104. Maximum Depth of Binary Tree
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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)
* }
*/
/**
* @description: 层序遍历的思想
* @param {TreeNode} root
* @return {number}
*/
const maxDepth = function (root) {
if (!root) {
return 0
}

let queue = [root]
let res = 0
while (queue.length) {
let curLength = queue.length
while (curLength) {
let cur = queue.shift()
if (cur.left) {
queue.push(cur.left)
}
if (cur.right) {
queue.push(cur.right)
}
curLength--
}
res++
}
return res
}