题目链接:https://leetcode-cn.com/problems/balance-a-binary-search-tree
题目描述:
给你一棵二叉搜索树,请你返回一棵 平衡后 的二叉搜索树,新生成的树应该与原来的树有着相同的节点值。
如果一棵二叉搜索树中,每个节点的两棵子树高度差不超过 1 ,我们就称这棵二叉搜索树是 平衡的 。
如果有多种构造方法,请你返回任意一种。
题解:
/**
* 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:
vector<int> tree;
TreeNode* balanceBST(TreeNode* root) {
inorder(root);
return build(0, tree.size() - 1);
}
void inorder(TreeNode* root)
{
if(root == nullptr)
return;
if(root->left != nullptr)
inorder(root->left);
tree.push_back(root->val);
if(root->right != nullptr)
inorder(root->right);
}
TreeNode* build(int left, int right)
{
if(left > right) return nullptr;
int mid = (left + right) / 2;
TreeNode* node = new TreeNode(tree[mid]);
node->left = build(left, mid - 1);
node->right = build(mid + 1, right);
return node;
}
};