Leetcode#669. 修剪二叉搜索树,C++实现

1. 题目

在这里插入图片描述

2. 方法一递归

2.1. 代码

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

2.2. 结果

在这里插入图片描述

3. 方法一非递归

3.1. 代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int L, int R) {
        queue<TreeNode*> temp;
        while(root!=NULL&&((root->val)<L||(root->val)>R)){
            if(root->val<L){ 
                root=root->right;
                continue;
            }
            if(root->val>R) root=root->left;
        }
        if(root==NULL) return root;
        temp.push(root);
        TreeNode* curr;
        while(!temp.empty()){
            curr=temp.front();
            temp.pop();
            
            while(curr->left!=NULL&&((curr->left->val)<L||(curr->left->val)>R)){
                if((curr->left->val)<L) {
                    curr->left=curr->left->right;
                    continue;
                }
                if((curr->left->val)>R) {
                    curr->left=curr->left->left;
                    continue;
                }
            }
            if(curr->left!=NULL) temp.push(curr->left);
            
            while(curr->right!=NULL&&((curr->right->val)<L||(curr->right->val)>R)){
                if((curr->right->val)<L) {
                    curr->right=curr->right->right;
                    continue;
                }
                if((curr->right->val)>R) {
                    curr->right=curr->right->left;
                    continue;
                }
            }
            if(curr->right!=NULL) temp.push(curr->right);
        }
    return root;  
    }
};

3.2. 结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值