forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Tree] Add a solution to Kth Smallest Element in a BST
- Loading branch information
Showing
2 changed files
with
44 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/kth-smallest-element-in-a-bst/ | ||
* Primary idea: use stack to do inorder traverse and track k to find answer | ||
* Time Complexity: O(n), Space Complexity: O(n) | ||
* | ||
* Definition for a binary tree node. | ||
* public class TreeNode { | ||
* public var val: Int | ||
* public var left: TreeNode? | ||
* public var right: TreeNode? | ||
* public init(_ val: Int) { | ||
* self.val = val | ||
* self.left = nil | ||
* self.right = nil | ||
* } | ||
* } | ||
*/ | ||
|
||
class KthSmallestElementBST { | ||
func kthSmallest(_ root: TreeNode?, _ k: Int) -> Int { | ||
var stack = [TreeNode](), currentNode = root, k = k | ||
|
||
while !stack.isEmpty || currentNode != nil { | ||
if currentNode != nil { | ||
stack.append(currentNode!) | ||
currentNode = currentNode!.left | ||
} else { | ||
let node = stack.removeLast() | ||
k -= 1 | ||
|
||
if k == 0 { | ||
return node.val | ||
} | ||
|
||
currentNode = node.right | ||
} | ||
} | ||
|
||
return -1 | ||
} | ||
} |