⬅ Previous Topic
Merge Two Binary Search TreesYou 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.
⬅ Previous Topic
Merge Two Binary Search TreesTopic Contents
k
.k
, record the current node's value as the kth largest element and terminate the traversal.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def kthLargest(root, k):
count = 0
result = None
def traverse(node):
nonlocal count, result
if not node or result is not None:
return
traverse(node.right)
count += 1
if count == k:
result = node.val
return
traverse(node.left)
traverse(root)
return result
# Example usage:
if __name__ == '__main__':
# Construct a sample BST:
# 5
# / \
# 3 7
# / \ \
# 2 4 8
root = TreeNode(5, TreeNode(3, TreeNode(2), TreeNode(4)), TreeNode(7, None, TreeNode(8)))
k = 2
print(kthLargest(root, k))
⬅ Previous Topic
Merge Two Binary Search TreesYou 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.