leetcode669. 修剪二叉搜索树

1.题目描述:

给你二叉搜索树的根节点root,同时给定最小边界low和最大边界high。通过修剪二叉搜索树,使得所有节点的值在[low,high]中。修剪树不应该改变保留在树中的元素的相对结构。可以证明,存在唯一的答案。所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。

2.递归:

leetcode701. 二叉搜索树中的插入操作leetcode450. 删除二叉搜索树中的节点和本题三者的递归都返回了处理完的当前root节点作为上级递归的左右子树,可以参考来看。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null) return root;
        if (root.val < low) return trimBST(root.right, low, high);//左子树全剪,返回修剪后的右子树root节点
        else if (root.val > high) return trimBST(root.left, low, high);//右子树全剪,返回修剪后的左子树root节点
        else {
            root.left = trimBST(root.left, low, high);//当前节点在范围内,则递归修建左右子树并相连
            root.right = trimBST(root.right, low, high);
        }
        return root;
    }
}

二刷:

class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null) return root;
        if (root.val > high) return trimBST(root.left, low, high);
        if (root.val < low) return trimBST(root.right, low, high);
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
        return root;
    }
}

3.迭代:

class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null) return root;
        while((root != null) && (root.val > high || root.val < low)) {//处理头节点使其位于[low,high]区间
            root = root.val > high ? root.left : root.right;
        }
        TreeNode temp = root;
        while (temp != null) {//迭代处理root左子树,修剪所有小于low的节点(左子树所有节点不会大于high)
            while (temp.left != null && temp.left.val < low) temp.left = temp.left.right;
            temp = temp.left;
        }
        temp = root;
        while (temp != null) {//迭代处理root右子树,修剪所有大于high的节点(右子树所有节点不会小于low)
            while (temp.right != null && temp.right.val > high) temp.right = temp.right.left;
            temp = temp.right;
        }
        return root;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值