Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 2

Question : check if a binary tree is a BST or not?

Answer : We can check whether a binary


tree is a BST or not by performing an inorder traversal of the binary tree and also checking
that the previous node's value is smaller than the current node's value.
# 5
# / \
# 3 7
# / \ / \
#1 4 6 8
root = TreeNode(5)
root.left = TreeNode(3)
root.right = TreeNode(7)
root.left.left = TreeNode(1)
root.left.right = TreeNode(4)
root.right.left = TreeNode(6)
root.right.right = TreeNode(8)

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 closest_value(root, target):


closest = root.val
while root:
if abs(root.val - target) < abs(closest - target):
closest = root.val
root = root.left if target < root.val else root.right
return closest

We can balance an unbalnce BST by


1. take inputs of nodes from the binary tree.
1. now we should define a function to find the height of tree.
2. now we should define a Boolean function to check recursively if the height
difference of left subtree and right subtree is not more than '1', then return True.
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None

def inorder_traversal(root, result):


if root:
inorder_traversal(root.left, result)
result.append(root.val)
inorder_traversal(root.right, result)

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)

You might also like