---
# System prepended metadata

title: LC 1382. Balance a Binary Search Tree
tags: [medium, leedcode, BST, python, c++]

---

# LC 1382. Balance a Binary Search Tree

### [Problem link](https://leetcode.com/problems/balance-a-binary-search-tree/)

###### tags: `leedcode` `python` `c++` `medium` `BST`

Given the <code>root</code> 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 <code>1</code>.

**Example 1:** 
<img alt="" src="https://assets.leetcode.com/uploads/2021/08/10/balance1-tree.jpg" style="width: 500px; height: 319px;" />
```
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:** 
<img alt="" src="https://assets.leetcode.com/uploads/2021/08/10/balanced2-tree.jpg" style="width: 224px; height: 145px;" />
```
Input: root = [2,1,3]
Output: [2,1,3]
```

 **Constraints:** 

- The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.
- <code>1 <= Node.val <= 10<sup>5</sup></code>

## Solution 1
#### Python
```python=
# 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
class Solution:
    def balanceBST(self, root: TreeNode) -> TreeNode:
        arr = []

        def traversal(node) -> None:
            if not node:
                return
            traversal(node.left)
            arr.append(node.val)
            traversal(node.right)

        traversal(root)

        def arr2BST(arr) -> TreeNode:
            if not arr:
                return None

            mid = len(arr) // 2
            head = TreeNode(arr[mid])

            head.left = arr2BST(arr[:mid])
            head.right = arr2BST(arr[mid + 1:])

            return head

        BST_root = arr2BST(arr)

        return BST_root
```
#### C++
```cpp=
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void Inorder(TreeNode *node, vector<int>& v) {
        if (node == nullptr) {
            return;
        }
        Inorder(node->left, v);
        v.push_back(node->val);
        Inorder(node->right, v);
    }

    TreeNode* Build(vector<int>& v, int left, int right) {
        if (left > right) {
            return nullptr;
        }
        int mid = left + (right - left) / 2;
        TreeNode *cur = new TreeNode(v[mid]);
        cur->left = Build(v, left, mid - 1);
        cur->right = Build(v, mid + 1, right);
        return cur;
    }

    TreeNode* balanceBST(TreeNode* root) {
        vector<int> v;
        Inorder(root, v);

        return Build(v, 0, v.size() - 1);
    }
};
```

>### Complexity
>n = The number of nodes in the tree
>|             | Time Complexity | Space Complexity |
>| ----------- | --------------- | ---------------- |
>| Solution 1  | O(n)            | O(n)             |


## Note
sol1:
traversal: TC(n), SC(n)
arr2BST: TC(n), SC(n)

total complexity: TC(n), SC(n)

Ref:
[Binary Tree Inorder Traversal (Recursive/Iteration)](https://hackmd.io/@Alone0506/HJqe9Qyra)
[LC 108. Convert Sorted Array to Binary Search Tree](https://hackmd.io/@Alone0506/HyxoauJnn)
