# 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
1
2
3
4
5
2
3
4
5
返回它的最大深度 3 。
题解:(深度优先搜索)DFS
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if(!root){
return 0;
}else{
let left = maxDepth(root.left);
let right = maxDepth(root.right);
return Math.max(left,right) + 1;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
题解:广度优先搜索 BFS
var maxDepth = function(root) {
if(root == null) return 0;
let queue = [root];
let maxDeep = 0;
while(queue.length){
let n = queue.length;
for(let i=0;i<n;i++){
let item = queue.shift();
if(item.left != null) queue.push(item.left);
if(item.right != null) queue.push(item.right);
}
maxDeep++;
}
return maxDeep
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15