forked from mehul-1607/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_104.java
54 lines (47 loc) · 1.43 KB
/
_104.java
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
47
48
49
50
51
52
53
54
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.LinkedList;
public class _104 {
public static class Solution1 {
/**
* Recursive solution:
* Time: O(n)
* Space: O(n)
*/
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
public static class Solution2 {
/**
* Iterative solution:
* Time: O(n)
* Space: O(n)
*/
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
LinkedList<TreeNode> stack = new LinkedList<>();
LinkedList<Integer> depths = new LinkedList<>();
stack.add(root);
depths.add(1);
int depth = 0;
while (!stack.isEmpty()) {
TreeNode currentNode = stack.pollLast();
int currentDepth = depths.pollLast();
if (currentNode != null) {
depth = Math.max(depth, currentDepth);
stack.add(currentNode.right);
depths.add(currentDepth + 1);
stack.add(currentNode.left);
depths.add(currentDepth + 1);
}
}
return depth;
}
}
}