力扣 669. 修剪二叉搜索树

文章提供了三种C++解决方案来修剪二叉搜索树,去除值不在给定范围(low,high)内的节点。方法包括递归法(两种不同实现)和迭代法。递归法通过对比节点值与边界值来决定修剪方向,而迭代法则通过移动根节点并处理左右子树来达到目标。
摘要由CSDN通过智能技术生成

题目来源:https://leetcode.cn/problems/trim-a-binary-search-tree/description/

 

 C++题解1:递归法。当前节点为空时返回空,不为空时对其值进行分类讨论。以low为例,当前节点值等于low时,意味着其左子树都要丢弃,可指向空;大于low时,说明其左子树也可能满足条件,因此对其左子树进一步递归;小于low时,说明当前节点及其左子树都不满足条件,将当前节点更新为其右子节点。

class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        if(!root) return nullptr;
        if(root->val == low) root->left = nullptr; 
        else if(root->val > low) {
            root->left = trimBST(root->left, low, high);
        }
        else {
            root = root->right;
            return trimBST(root, low, high);
        }
        if(root->val == high) root->right = nullptr;
        else if(root->val < high) {
            root->right = trimBST(root->right, low, high);
        }
        else {
            root = root->left;
            return trimBST(root, low, high);
        }
        return root;
    }
};

C++题解2:递归法。大致思路同上,较为精简,来源代码随想录

class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        if (root == nullptr) return nullptr;
        if (root->val < low) return trimBST(root->right, low, high);
        if (root->val > high) return trimBST(root->left, low, high);
        root->left = trimBST(root->left, low, high);
        root->right = trimBST(root->right, low, high);
        return root;
    }
};

C++题解3:迭代法。见注释,来源代码随想录

class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int L, int R) {
        if (!root) return nullptr;

        // 处理头结点,让root移动到[L, R] 范围内,注意是左闭右闭
        while (root != nullptr && (root->val < L || root->val > R)) {
            if (root->val < L) root = root->right; // 小于L往右走
            else root = root->left; // 大于R往左走
        }
        TreeNode *cur = root;
        // 此时root已经在[L, R] 范围内,处理左孩子元素小于L的情况
        while (cur != nullptr) {
            while (cur->left && cur->left->val < L) {
                cur->left = cur->left->right;
            }
            cur = cur->left;
        }
        cur = root;

        // 此时root已经在[L, R] 范围内,处理右孩子大于R的情况
        while (cur != nullptr) {
            while (cur->right && cur->right->val > R) {
                cur->right = cur->right->left;
            }
            cur = cur->right;
        }
        return root;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值