forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0230-kth-smallest-element-in-a-bst.scala
More file actions
36 lines (34 loc) · 1.01 KB
/
0230-kth-smallest-element-in-a-bst.scala
File metadata and controls
36 lines (34 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for a binary tree node.
* class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
* var value: Int = _value
* var left: TreeNode = _left
* var right: TreeNode = _right
* }
*/
object Solution {
def kthSmallest(root: TreeNode, k: Int): Int = {
helper(root, k)._2
}
// Recursive in-order traversal.
def helper(root: TreeNode, k: Int): (Boolean, Int, Int) = {
if (root == null) {
return (false, 0, 0)
}
val (isInLeft, lVal, lSize) = helper(root.left, k)
if (isInLeft) {
return (true, lVal, 0)
} else {
if (k - lSize == 1) {
return (true, root.value, 0)
} else {
val (isInRight, rVal, rSize) = helper(root.right, k - (lSize + 1))
if (isInRight) {
return (true, rVal, 0)
} else {
return (false, 0, lSize + rSize + 1)
}
}
}
}
}