Next Topic ⮕
Balance a Binary Search TreeYou 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.
Next Topic ⮕
Balance a Binary Search Treeclass TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorderTraversal(root, arr):
if root:
inorderTraversal(root.left, arr)
arr.append(root.val)
inorderTraversal(root.right, arr)
def arrayToBST(root, arr_iter):
if root:
arrayToBST(root.left, arr_iter)
root.val = next(arr_iter)
arrayToBST(root.right, arr_iter)
def binaryTreeToBST(root):
arr = []
inorderTraversal(root, arr)
arr.sort()
arr_iter = iter(arr)
arrayToBST(root, arr_iter)
return root
# Example usage:
if __name__ == '__main__':
# Construct binary tree:
# 10
# / \
# 30 15
# / \
# 20 5
root = TreeNode(10, TreeNode(30, TreeNode(20)), TreeNode(15, None, TreeNode(5)))
binaryTreeToBST(root)
result = []
inorderTraversal(root, result)
print(result)
Next Topic ⮕
Balance a Binary Search TreeYou 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.