⬅ Previous Topic
Find the kth Largest Element in a Binary Search TreeNext Topic ⮕
Flatten a Binary Search Tree into a Sorted List⬅ Previous Topic
Find the kth Largest Element in a Binary Search TreeNext Topic ⮕
Flatten a Binary Search Tree into a Sorted ListTopic Contents
k
.k
, record the current node's value as the kth smallest element.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
self.count = 0
self.ans = None
def inorder(node):
if not node or self.ans is not None:
return
inorder(node.left)
self.count += 1
if self.count == k:
self.ans = node.val
return
inorder(node.right)
inorder(root)
return self.ans
# Example usage:
if __name__ == '__main__':
# Construct BST:
# 3
# / \
# 1 4
# \
# 2
root = TreeNode(3, TreeNode(1, None, TreeNode(2)), TreeNode(4))
sol = Solution()
print(sol.kthSmallest(root, 1))
⬅ Previous Topic
Find the kth Largest Element in a Binary Search TreeNext Topic ⮕
Flatten a Binary Search Tree into a Sorted ListYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.