Given the root
of a binary search tree (BST) and an integer k
, return the kth
smallest element in the tree.
Input: root = [3,1,4,null,2], k = 1
Output: 1
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
n
.k
nodes, the kth
node’s value is the kth
smallest element.inorder
traversal (Left, Root, Right).k
.k
nodes.# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def kthSmallest(root: TreeNode, k: int) -> int:
stack = []
current = root
count = 0
# Inorder traversal loop
while stack or current:
# Reach the left most Node of the current Node
while current:
stack.append(current)
current = current.left
# current must be None at this point
current = stack.pop()
count += 1
# If count is equal to k, return the current node's value
if count == k:
return current.val
# Move to the right subtree
current = current.right
# Example Usage:
# Let's create a test tree [3,1,4,null,2]
# 3
# / \
# 1 4
# \
# 2
root = TreeNode(3)
root.left = TreeNode(1)
root.right = TreeNode(4)
root.left.right = TreeNode(2)
k = 1
print(kthSmallest(root, k)) # Output: 1
Explanation:
count
variable ensures that we stop and return the kth
node’s value.This approach ensures we efficiently find the kth
smallest element without the need for additional space beyond the recursion stack or maintaining a separate sorted list of elements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?