leetcode 1382 将二叉搜索树变平衡

简介: leetcode 1382 将二叉搜索树变平衡

将二叉搜索树变平衡

/**
 * 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> nums;
    void track_back(TreeNode* cur)
    {
        if(cur == nullptr) return;
        track_back(cur->left);
        nums.push_back(cur->val);
        track_back(cur->right);
        return;
    }
    TreeNode* make_tree(vector<int> &nums , int left ,int right)
    {
        if(left > right) return nullptr;
        int mid = left + (right - left)/2;
        TreeNode* new_root = new TreeNode(nums[mid]);
        new_root->left = make_tree(nums , left ,mid-1);
        new_root->right = make_tree(nums , mid+1 ,right);
        return new_root;
    }
    TreeNode* balanceBST(TreeNode* root) {
        track_back(root);
        return make_tree(nums,0,nums.size()-1);
    }
};
相关文章
|
机器学习/深度学习 存储 算法
LeetCode 题目 95:从递归到动态规划实现 不同的二叉搜索树 II
LeetCode 题目 95:从递归到动态规划实现 不同的二叉搜索树 II
|
Python
【Leetcode刷题Python】450. 删除二叉搜索树中的节点
LeetCode上538号问题"把二叉搜索树转换为累加树"的Python实现,使用反向中序遍历并记录节点值之和来更新每个节点的新值。
359 4
【Leetcode刷题Python】450. 删除二叉搜索树中的节点
|
Python
【Leetcode刷题Python】96. 不同的二叉搜索树
LeetCode 96题 "不同的二叉搜索树" 的Python解决方案,使用动态规划算法计算由1至n互不相同节点值组成的二叉搜索树的种数。
301 3
【Leetcode刷题Python】96. 不同的二叉搜索树
【LeetCode 45】701.二叉搜索树中的插入操作
【LeetCode 45】701.二叉搜索树中的插入操作
245 1
【LeetCode 44】235.二叉搜索树的最近公共祖先
【LeetCode 44】235.二叉搜索树的最近公共祖先
257 1
|
算法 Python
【Leetcode刷题Python】剑指 Offer 33. 二叉搜索树的后序遍历序列
本文提供了一种Python算法,用以判断给定整数数组是否为某二叉搜索树的后序遍历结果,通过识别根节点并递归验证左右子树的值是否满足二叉搜索树的性质。
290 3
|
Python
【Leetcode刷题Python】538. 把二叉搜索树转换为累加树
LeetCode上538号问题"把二叉搜索树转换为累加树"的Python实现,使用反向中序遍历并记录节点值之和来更新每个节点的新值。
269 3
|
Python
【Leetcode刷题Python】108. 将有序数组转换为二叉搜索树
LeetCode上108号问题"将有序数组转换为二叉搜索树"的Python实现,通过递归选取数组中间值作为根节点,构建高度平衡的二叉搜索树。
291 2
LeetCode第96题不同的二叉搜索树
文章介绍了LeetCode第96题"不同的二叉搜索树"的解法,利用动态规划的思想和递推公式,通过计算以任意节点为根的不同二叉搜索树的数量,解决了该问题。
LeetCode第96题不同的二叉搜索树
【LeetCode 48】108.将有序数组转换为二叉搜索树
【LeetCode 48】108.将有序数组转换为二叉搜索树
257 0

热门文章

最新文章