Skip to content

Commit 03c56f4

Browse files
committed
add solution of valid-binary-search-tree using iterative DFS
1 parent 9f0c962 commit 03c56f4

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

โ€Žvalidate-binary-search-tree/jinhyungrhee.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ class Solution {
4343
public boolean isValidBST(TreeNode root) {
4444

4545
dfs(root);
46+
// iterativeDFS(root);
4647

4748
if (orderedList.isEmpty()) return false;
4849
for (int i = 0; i < orderedList.size() - 1; i++) {
@@ -65,4 +66,33 @@ public void dfs(TreeNode node) {
6566
if (node.right != null) dfs(node.right);
6667

6768
}
69+
70+
71+
/**
72+
runtime : 9ms
73+
memory : 45.41mb
74+
*/
75+
76+
// [idea] : ์˜ค๋ฅธ์ชฝ sub-tree๋กœ ์ด๋™ํ•˜๋ฉฐ ์•„๋ž˜์˜ 1-2-3 ๊ณผ์ • ๋ฐ˜๋ณต ์ˆ˜ํ–‰
77+
// [time-complexity] : O(N)
78+
// [space-complexity] : O(N)
79+
80+
public void iterativeDFS(TreeNode root) {
81+
82+
Deque<TreeNode> stack = new ArrayDeque<>();
83+
TreeNode current = root;
84+
while (current != null || !stack.isEmpty()) {
85+
86+
// 1. ์™ผ์ชฝ์˜ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๊ณ„์†ํ•ด์„œ stack์— push
87+
while (current != null) {
88+
stack.push(current);
89+
current = current.left;
90+
}
91+
// 2. ์™ผ์ชฝ ๋…ธ๋“œ ๋์— ๋„๋‹ฌํ•˜๋ฉด ์Šคํƒ์—์„œ ๊บผ๋‚ด์„œ ๋ฐฉ๋ฌธ
92+
current = stack.pop();
93+
orderedList.add(current.val);
94+
// 3. ์˜ค๋ฅธ์ชฝ ๋…ธ๋“œ๋กœ ์ด๋™
95+
current = current.right;
96+
}
97+
}
6898
}

0 commit comments

Comments
ย (0)