Skip to content

Commit 667fea8

Browse files
add one more iterative solution for 144
1 parent f442f51 commit 667fea8

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,21 @@ List<Integer> pre(TreeNode root, List<Integer> list) {
5858
return list;
5959
}
6060
}
61+
62+
public static class Solution3 {
63+
public List<Integer> preorderTraversal(TreeNode root) {
64+
List<Integer> list = new ArrayList<>();
65+
Stack<TreeNode> stack = new Stack<>();
66+
while (!stack.isEmpty() || root != null) {
67+
while (root != null) {
68+
list.add(root.val);
69+
stack.push(root);
70+
root = root.left;
71+
}
72+
root = stack.pop();
73+
root = root.right;
74+
}
75+
return list;
76+
}
77+
}
6178
}

src/test/java/com/fishercoder/_144Test.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,15 @@
1414
public class _144Test {
1515
private static _144.Solution1 solution1;
1616
private static _144.Solution2 solution2;
17+
private static _144.Solution3 solution3;
1718
private static TreeNode root;
1819
private static List<Integer> inorder;
1920

2021
@BeforeClass
2122
public static void setup() {
2223
solution1 = new _144.Solution1();
2324
solution2 = new _144.Solution2();
25+
solution3 = new _144.Solution3();
2426
}
2527

2628
@Test
@@ -53,4 +55,20 @@ public void test4() {
5355
assertEquals(Arrays.asList(1, 2, 4, 7, 8, 9, 3, 5, 6), inorder);
5456
}
5557

58+
@Test
59+
public void test5() {
60+
root = TreeUtils.constructBinaryTree(Arrays.asList(1, 2, 3, 4, null, 5, null, null, 6));
61+
TreeUtils.printBinaryTree(root);
62+
inorder = solution1.preorderTraversal(root);
63+
assertEquals(Arrays.asList(1, 2, 4, 6, 3, 5), inorder);
64+
}
65+
66+
@Test
67+
public void test6() {
68+
root = TreeUtils.constructBinaryTree(Arrays.asList(1, 2, 3, 4, null, 5, null, null, 6));
69+
TreeUtils.printBinaryTree(root);
70+
inorder = solution3.preorderTraversal(root);
71+
assertEquals(Arrays.asList(1, 2, 4, 6, 3, 5), inorder);
72+
}
73+
5674
}

0 commit comments

Comments
 (0)