Leetcode 1382. Balance a Binary Search Tree 看上去难但简单的medium题

  • 平衡一棵二叉树,第一反应是上课讲过的RR RL LL LR旋转,代码实现较难,很厉害的选手也得几十分钟写出

  • 但这里的情况是,已经给定一棵二叉搜索树了,故其实已经排好序了,只要把数据再重新插入到一棵平衡二叉树中即可

  • 所以可看成两个步骤:

    • 中序遍历给定的树,得到排好序的数组
    • 将有序数组转变为二叉搜索树
  • 两个步骤之前都有相应的代码 link1, link2

/**
 * 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:
    TreeNode* balanceBST(TreeNode* root) {
        inorder(root);
        return build(nums, 0, nums.size()-1);
    }
private:
    vector<int> nums;
    void inorder(TreeNode* root){
        if(!root) return ;
        inorder(root->left);
        nums.push_back(root->val);
        inorder(root->right);
    }
    
    TreeNode* build(const vector<int> nums, int l, int r){
        if(l>r) return nullptr;
        int m  = l+(r-l)/2;
        TreeNode* root = new TreeNode(nums[m]);
        root->left = build(nums, l, m-1);
        root->right = build(nums, m+1, r);
        return root;
    }
    
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章