File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
validate-binary-search-tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change @@ -43,6 +43,7 @@ class Solution {
43
43
public boolean isValidBST (TreeNode root ) {
44
44
45
45
dfs (root );
46
+ // iterativeDFS(root);
46
47
47
48
if (orderedList .isEmpty ()) return false ;
48
49
for (int i = 0 ; i < orderedList .size () - 1 ; i ++) {
@@ -65,4 +66,33 @@ public void dfs(TreeNode node) {
65
66
if (node .right != null ) dfs (node .right );
66
67
67
68
}
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
+ }
68
98
}
You can’t perform that action at this time.
0 commit comments