Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1757 from ChrisKheng/scala
Browse files Browse the repository at this point in the history
Create 0230-kth-smallest-element-in-a-bst.scala
  • Loading branch information
Ahmad-A0 authored Jan 1, 2023
2 parents e38a90c + 6d1fe24 commit 3631135
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions scala/0230-kth-smallest-element-in-a-bst.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,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)
}
}
}
}
}

0 comments on commit 3631135

Please sign in to comment.