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)