230. Kth Smallest Element in a BST
Description
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
Thoughts
We can simply use inorder traversal to find the kth elements.
We can also use stack to implement inorder traversal without using recursive coding.
Code
inorder traversal
'''
use in order traversal to get all the node.val in a list
the kth elements is the kth smallest
'''
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
value_list = self.inorder_traversal(root)
return value_list[k - 1]
def inorder_traversal(self, root):
if not root:
return []
left = self.inorder_traversal(root.left)
right = self.inorder_traversal(root.right)
return left + [root.val] + right
}
stack
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
'''
initialize an empty stack
'''
stack = []
'''
put the root and all the left nodes to the stack
now the stack has root in the bottom
the smallest node (left most node) is on the top
'''
while root:
stack.append(root)
root = root.left
'''
we need to get the Kth smallest so we need to pop k-1 times
pop the smallest node first
'''
for i in range(k-1):
node = stack.pop()
'''
if the node has right subtree:
based on BST definition, all the nodes in the right
subtree are smaller than the parent node of the current
node.
8
/
2
/ \
1 4
/ \
3 5
in stack: 1 -- 2 -- 8
pop 1 frist and then pop 2
3, 4, 5 in the right subtree are all smaller than 8
need to append them in the stack above 8
and they will be pop before 8
'''
if node.right:
node = node.right
'''
look at the right node, and put all the left nodes in stack
3 -- 4 -- 8
'''
while node:
stack.append(node)
node = node.left
'''
pop 3, 4 and 4 has right node 5
put 5 in : 5 -- 8
'''
return stack[-1].val