Skip to content

Commit 2a37bb0

Browse files
refactor 104
1 parent a1067c0 commit 2a37bb0

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/main/java/com/fishercoder/solutions/_104.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import com.fishercoder.common.classes.TreeNode;
44

5+
import java.util.LinkedList;
6+
57
/**
68
* 104. Maximum Depth of Binary Tree
79
*
@@ -25,6 +27,7 @@ public class _104 {
2527

2628
public static class Solution1 {
2729
/**
30+
* Recursive solution:
2831
* Time: O(n)
2932
* Space: O(n)
3033
*/
@@ -36,4 +39,35 @@ public int maxDepth(TreeNode root) {
3639
}
3740
}
3841

42+
public static class Solution2 {
43+
/**
44+
* Iterative solution:
45+
* Time: O(n)
46+
* Space: O(n)
47+
*/
48+
public int maxDepth(TreeNode root) {
49+
if (root == null) {
50+
return 0;
51+
}
52+
LinkedList<TreeNode> stack = new LinkedList<>();
53+
LinkedList<Integer> depths = new LinkedList<>();
54+
stack.add(root);
55+
depths.add(1);
56+
57+
int depth = 0;
58+
while (!stack.isEmpty()) {
59+
TreeNode currentNode = stack.pollLast();
60+
int currentDepth = depths.pollLast();
61+
if (currentNode != null) {
62+
depth = Math.max(depth, currentDepth);
63+
stack.add(currentNode.right);
64+
depths.add(currentDepth + 1);
65+
stack.add(currentNode.left);
66+
depths.add(currentDepth + 1);
67+
}
68+
}
69+
return depth;
70+
}
71+
}
72+
3973
}

src/test/java/com/fishercoder/_104Test.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,25 @@
1313

1414
public class _104Test {
1515
private static _104.Solution1 solution1;
16+
private static _104.Solution2 solution2;
1617
private static TreeNode root;
1718

1819
@BeforeClass
1920
public static void setup() {
2021
solution1 = new _104.Solution1();
22+
solution2 = new _104.Solution2();
2123
}
2224

2325
@Test
2426
public void test1() {
2527
root = TreeUtils.constructBinaryTree(Arrays.asList(3, 9, 20, null, null, 15, 7));
2628
assertEquals(3, solution1.maxDepth(root));
2729
}
30+
31+
@Test
32+
public void test2() {
33+
root = TreeUtils.constructBinaryTree(Arrays.asList(3, 9, 20, null, null, 15, 7));
34+
TreeUtils.printBinaryTree(root);
35+
assertEquals(3, solution2.maxDepth(root));
36+
}
2837
}

0 commit comments

Comments
 (0)