Created
September 21, 2015 18:33
-
-
Save junjiah/8be94115ca6831c43bfe to your computer and use it in GitHub Desktop.
solved 'Kth Smallest Element in a BST' on LeetCode https://leetcode.com/problems/kth-smallest-element-in-a-bst/
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
# Memoize the size and iteratively get down. | |
# Bad because getting size requires O(n) time. | |
class Solution(object): | |
def kthSmallest(self, root, k): | |
""" | |
:type root: TreeNode | |
:type k: int | |
:rtype: int | |
""" | |
self.sz_dict = {None: 0} | |
while root: | |
sz_left = self.get_size(root.left) | |
if sz_left == k - 1: | |
return root.val | |
elif sz_left >= k: | |
root = root.left | |
else: | |
root = root.right | |
k -= 1 + sz_left | |
# Should never reach here. | |
return -1 | |
def get_size(self, root): | |
if not root: | |
return 0 | |
sz = self.sz_dict.get(root, -1) | |
if sz == -1: | |
sz = self.get_size(root.left) + self.get_size(root.right) + 1 | |
self.sz_dict[root] = sz | |
return sz |
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
# In order traversal using stack. K-th iteration returns | |
# k-th smallest. | |
class Solution(object): | |
def kthSmallest(self, root, k): | |
""" | |
:type root: TreeNode | |
:type k: int | |
:rtype: int | |
""" | |
# Use stack for in-order traversal. | |
st, curr = [], root | |
# Since k is always valid, so the | |
# loop is guaranteed to end. | |
while True: | |
if curr: | |
st.append(curr) | |
curr = curr.left | |
else: | |
curr = st.pop() | |
k -= 1 | |
# Matched k-th smallest. | |
if k == 0: | |
return curr.val | |
curr = curr.right |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment