[LeetCode] Balance a Binary Search Tree

1382. Balance a Binary Search Tree

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* 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 {
vector<TreeNode*> orderedNode;
void pushRecursive(TreeNode* node) {
if(!node) return;
pushRecursive(node->left);
orderedNode.push_back(node);
pushRecursive(node->right);
}

TreeNode* reorder(int s, int e) {
if(s > e) return NULL;
int m = (s + e) >> 1;
TreeNode* head = orderedNode[m];
head->left = reorder(s, m - 1);
head->right = reorder(m + 1, e);
return head;
}
public:
TreeNode* balanceBST(TreeNode* root) {
pushRecursive(root);
return reorder(0, orderedNode.size() - 1);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/10/PS/LeetCode/balance-a-binary-search-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.