Skip to content

Commit 5441d88

Browse files
Sync LeetCode submission Runtime - 4 ms (85.25%), Memory - 65.8 MB (38.96%)
1 parent 333acf5 commit 5441d88

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<p>Given the <code>root</code> of a binary search tree, return <em>a <strong>balanced</strong> binary search tree with the same node values</em>. If there is more than one answer, return <strong>any of them</strong>.</p>
2+
3+
<p>A binary search tree is <strong>balanced</strong> if the depth of the two subtrees of every node never differs by more than <code>1</code>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
<img alt="" src="https://assets.leetcode.com/uploads/2021/08/10/balance1-tree.jpg" style="width: 500px; height: 319px;" />
8+
<pre>
9+
<strong>Input:</strong> root = [1,null,2,null,3,null,4,null,null]
10+
<strong>Output:</strong> [2,1,3,null,null,null,4]
11+
<b>Explanation:</b> This is not the only correct answer, [3,1,4,null,2] is also correct.
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
<img alt="" src="https://assets.leetcode.com/uploads/2021/08/10/balanced2-tree.jpg" style="width: 224px; height: 145px;" />
16+
<pre>
17+
<strong>Input:</strong> root = [2,1,3]
18+
<strong>Output:</strong> [2,1,3]
19+
</pre>
20+
21+
<p>&nbsp;</p>
22+
<p><strong>Constraints:</strong></p>
23+
24+
<ul>
25+
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
26+
<li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
27+
</ul>
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
vector<int> vals;
14+
void dfs(TreeNode* node) {
15+
if (node == nullptr) return;
16+
dfs(node->left);
17+
vals.push_back(node->val);
18+
dfs(node->right);
19+
}
20+
21+
TreeNode* construct(int l, int r) {
22+
if (l > r) return nullptr;
23+
int m = (l + r) / 2;
24+
TreeNode* root = new TreeNode(vals[m]);
25+
root->left = construct(l, m-1);
26+
root->right = construct(m+1, r);
27+
return root;
28+
}
29+
30+
public:
31+
TreeNode* balanceBST(TreeNode* root) {
32+
vals.clear();
33+
dfs(root);
34+
root = construct(0, vals.size()-1);
35+
return root;
36+
}
37+
};

0 commit comments

Comments
 (0)