[leetcode]maximum depth of binary tree

题目描述

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

代码

可以用DFS方法

1
2
3
4
5
6
7
public class {

public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}

也可以用BFS

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
public class {
//BFS,每个节点都会进队列一次,节点出队列时统计即可
public int maxDepth1(TreeNode root) {
if(root == null) return 0;

Queue<TreeNode> queue = new LinkedList<>();

queue.offer(root);
int level = 0;
while(!queue.isEmpty()){
level++;

int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
}
}
return level;
}
}