Professional Documents
Culture Documents
Untitled 2
Untitled 2
print(is_bst(root))
# Output: True
# 5
# / \
# 3 7
# / \ / \
# 1 6 4 8
root.left.right.val = 6
print(is_bst(root))
# Output: False
Ques 2 : find the closest element in the bst ?? to find the closest element in a Binary Search
Tree to a given target value. we can perform we can perform transversal through the tree
while also keeping the track of the closest node enountered.
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def sorted_array_to_bst(nums):
if not nums:
return None
mid = len(nums) // 2
root = TreeNode(nums[mid])
root.left = sorted_array_to_bst(nums[:mid])
root.right = sorted_array_to_bst(nums[mid+1:])
return root
def balance_bst(root):
sorted_elements = []
inorder_traversal(root, sorted_elements)
return sorted_array_to_bst(sorted_elements)
root = TreeNode(101)
root.left = TreeNode(52)
root.right = TreeNode(223)
root.right.right = TreeNode(258)
balanced_root = balance_bst(root)