-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution104.java
More file actions
46 lines (40 loc) · 1.22 KB
/
Copy pathSolution104.java
File metadata and controls
46 lines (40 loc) · 1.22 KB
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
42
43
44
45
46
package solution101to150;
import common.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
import javafx.util.Pair;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// Leetcode 104. Maximum Depth of Binary Tree
public class Solution104 {
// Case 1: Recursion
public int maxDepth(TreeNode root) {
return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
// Case 2: Iteration
public int maxDepthIteration(TreeNode root) {
Queue<Pair<TreeNode, Integer>> stack = new LinkedList<>();
if (root != null) {
stack.add(new Pair(root, 1));
}
int depth = 0;
while (!stack.isEmpty()) {
Pair<TreeNode, Integer> current = stack.poll();
root = current.getKey();
int current_depth = current.getValue();
if (root != null) {
depth = Math.max(depth, current_depth);
stack.add(new Pair(root.left, current_depth + 1));
stack.add(new Pair(root.right, current_depth + 1));
}
}
return depth;
}
}