0
点赞
收藏
分享

微信扫一扫

LeetCode 699 修剪二叉搜索树

老北京的热干面 2022-04-04 阅读 29

   public TreeNode trimBST(TreeNode root, int low, int high) {

        if (root == null) {

            return root;

        }

        // 如果当前节点的值小于 最小值  则将右子节点赋给当前节点

         //如果当前节点的值大于 最大值  则将左子节点赋给当前节点

        while(root != null && (root.val < low || root.val > high )){

           if(root != null && root.val < low) {

                root = root.right;

            }

            if (root != null && root.val > high) {

            root = root.left;

            }

        }

        if(root != null){

            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 null;
        }
        if (root.val < low) {
            return trimBST(root.right, low, high);
        }
        if (root.val > high) {
            return trimBST(root.left, low, high);
        }
        // root在[low,high]范围内
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
        return root;
    }
}
举报

相关推荐

0 条评论