Create Balanced BST

Problem is here: https://leetcode.com/problems/balance-a-binary-search-tree/

1382. Balance a Binary Search Tree
Medium
Given a binary search tree, return a balanced binary search tree with the same node values.
A binary search tree is balanced if and only if the depth of the two subtrees of every node never differ by more than 1.
If there is more than one answer, return any of them.

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,null,null] is also correct.

Constraints:
  • The number of nodes in the tree is between 1 and 10^4.
  • The tree nodes will have distinct values between 1 and 10^5.

There is a standard way to create a balanced BST from a sorted array, which is this:

1) Get the Middle of the array and make it root.
2) Recursively do same for left half and right half.
      a) Get the middle of left half and make it left child of the root
          created in step 1.
      b) Get the middle of right half and make it right child of the
          root created in step 1.

To get the sorted array from the initial BST, perform an in-order traversal. Code is below, cheers, ACC.



public class Solution
{
    public TreeNode BalanceBST(TreeNode root)
    {
        List<int> list = new List<int>();
        InOrder(root, list);
        int[] sortedArr = list.ToArray<int>();
        return CreateBalanceBST(sortedArr, 0, sortedArr.Length - 1);
    }

    private TreeNode CreateBalanceBST(int[] sortedArr, int left, int right)
    {
        if (left > right) return null;
        int mid = (left + right) / 2;
        TreeNode node = new TreeNode(sortedArr[mid]);
        node.left = CreateBalanceBST(sortedArr, left, mid - 1);
        node.right = CreateBalanceBST(sortedArr, mid + 1, right);
        return node;
    }

    private void InOrder(TreeNode node,
                            List<int> list)
    {
        if (node == null) return;
        InOrder(node.left, list);
        list.Add(node.val);
        InOrder(node.right, list);
    }
}

Comments

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Golang vs. C#: performance characteristics (simple case study)

Advent of Code - Day 7, 2024: Backtracking and Eval