Solving Leetcode Interviews in Seconds with AI: Balance a Binary Search Tree
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1382" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them. A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1. Example 1: Input: root = [1,null,2,null,3,null,4,null,null] Output: [2,1,3,null,null,null,4] Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct. Example 2: Input: root = [2,1,3] Output: [2,1,3] Constraints: The number of nodes in the tree is in the range [1, 104]. 1 <= Node.val <= 105
Explanation
Here's the breakdown of the solution:
- Inorder Traversal: Perform an inorder traversal of the given BST to extract all node values in sorted order. This is crucial because a balanced BST can be efficiently constructed from a sorted array.
- Sorted Array to Balanced BST: Use the sorted array obtained from the inorder traversal to construct a balanced BST recursively. The middle element of the sorted array becomes the root, and the left and right halves of the array are used to build the left and right subtrees, respectively.
Return the Balanced BST: The function returns the root of the newly constructed balanced BST.
Runtime Complexity: O(N), where N is the number of nodes in the tree.
- Storage Complexity: O(N), mainly due to the storage of the inorder traversal result in a list.
Code
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def balanceBST(root: TreeNode) -> TreeNode:
"""
Given a BST, return a balanced BST with the same node values.
"""
def inorder_traversal(node: TreeNode, nodes: list):
"""Performs inorder traversal to get sorted node values."""
if node:
inorder_traversal(node.left, nodes)
nodes.append(node.val)
inorder_traversal(node.right, nodes)
def build_balanced_bst(nodes: list) -> TreeNode:
"""Builds a balanced BST from a sorted array."""
if not nodes:
return None
mid = len(nodes) // 2
root = TreeNode(nodes[mid])
root.left = build_balanced_bst(nodes[:mid])
root.right = build_balanced_bst(nodes[mid + 1:])
return root
nodes = []
inorder_traversal(root, nodes)
return build_balanced_bst(nodes)