11.26 log

450.删除二叉搜索树中的节点

class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if(root==NULL) return NULL;
        if(root->val==key){
            if(!root->left&&!root->right){
                delete root;
                return NULL;
            }
            else if(!root->left&&root->right){
                TreeNode* temp=root->right;
                delete root;
                return temp;
            }
            else if(root->left&&!root->right){
                TreeNode* temp=root->left;
                delete root;
                return temp;
            }
            else{
                TreeNode* cur=root->right;
                while(cur->left) cur=cur->left;
                cur->left=root->left;
                TreeNode* temp=root->right;
                delete root;
                return temp;
            }
        }
        if(root->val>key) root->left=deleteNode(root->left,key);
        if(root->val<key) root->right=deleteNode(root->right,key);
        return root;
    }
};

递归参数为根节点,删除的目标值,返回值为根节点,终止条件为当递归到空节点时返回空,当递归到与目标值相等时,判断root左右节点的情况,分为四种,一,root为叶子节点,直接删除root返回NULL;二、三,root子节点有一个为空,root节点指向不为空的那个节点并返回,删除root;四,root两个子节点都不为空,可以root指向root->right,然后右子树的最左叶子节点的左节点指向root->left,删除root,递归内部逻辑为当root值大于key,向左递归,并用root->left接住返回值,当root值小于key时反之则反,最后返回值为每一层的root

669. 修剪二叉搜索树

class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        if(root==NULL) return NULL;
        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;
    } 
};

递归参数为根节点,左边界,右边界,返回值为修剪后的节点,终止条件为当root为空时返回空,当root值小于左边界时向右子树递归,因为左子树一定是小于左边界的,而右子树可能在边界内,当root值大于右边界时向左子树递归,一样的道理。递归的内部逻辑为左子树向左递归,右子树向右递归,最后返回每一层的子树

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值