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