File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
kth-smallest-element-in-a-bst Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ package leetcode_study
2+
3+ /* *
4+ * binary search tree์์ k ๋ฒ์งธ ์์ ์๋ฅผ ๋ฐํํ๋ ๋ฌธ์
5+ * stack ์๋ฃ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํด ์ค์ ์ํ๋ฅผ ๊ตฌํํฉ๋๋ค.
6+ *
7+ * ์๊ฐ ๋ณต์ก๋: O(n) or O(logn)
8+ * -> 2๋ฒ์ loop์ ์ํํ๊ธฐ ๋๋ฌธ์ O(n^2)์ ์๊ฐ ๋ณต์ก๋๋ก ํ๋จํ ์ ์์ง๋ง ์ ํ๋ n ์์์ ์ํ๋ฅผ ์งํํ๊ธฐ ๋๋ฌธ์ O(n)์ ๋์ง ์์ต๋๋ค.
9+ * -> ๋ง์ฝ BST๊ฐ ๊ท ํ์ด ์กํ ์๋ค๋ฉด O(logn)์ ์๊ฐ ๋ณต์ก๋๋ฅผ ๊ฐ์ต๋๋ค.
10+ *
11+ * ๊ณต๊ฐ ๋ณต์ก๋: O(n)
12+ * -> ํ์ํ node๋ฅผ ์ ์ฅํ stack ๊ณต๊ฐ
13+ */
14+ fun kthSmallest (root : TreeNode ? , k : Int ): Int {
15+ val stack = ArrayDeque <TreeNode >()
16+ var current = root
17+ var count = 0
18+
19+ while (stack.isNotEmpty() || current != null ) {
20+ // ์ผ์ชฝ ์์ ๋
ธ๋๋ค์ ๊ณ์ ํ์ํ์ฌ stack์ ์ถ๊ฐ
21+ while (current != null ) {
22+ stack.addLast(current)
23+ current = current.left
24+ }
25+
26+ // ๊ฐ์ฅ ์ผ์ชฝ ๋
ธ๋๋ฅผ pop
27+ current = stack.removeLast()
28+ count++
29+
30+ // k๋ฒ์งธ ๋
ธ๋๋ผ๋ฉด ๊ฐ ๋ฐํ
31+ if (count == k) return current.`val `
32+
33+ // ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ ํ์
34+ current = current.right
35+ }
36+
37+ return - 1 // ์ด๋ก ์ ์ผ๋ก ๋๋ฌํ ์ ์๋ ๋ถ๋ถ
38+ }
You canโt perform that action at this time.
0 commit comments