forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumDepthOfBinaryTree.java
More file actions
41 lines (38 loc) · 975 Bytes
/
MaximumDepthOfBinaryTree.java
File metadata and controls
41 lines (38 loc) · 975 Bytes
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
package com.examplehub.leetcode.easy;
import com.examplehub.leetcode.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
public class MaximumDepthOfBinaryTree {
public static int solution1(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = solution1(root.left);
int rightHeight = solution1(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
public static int solution2(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int answer = 0;
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
TreeNode node = queue.poll();
assert node != null;
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
size--;
}
answer++;
}
return answer;
}
}