Java noun recursive solution


  • 0
    A
    class Solution {
        public TreeNode trimBST(TreeNode root, int L, int R) {
            if(L == R)  return new TreeNode(L);
            root = findNewRoot(root, L, R);
            TrimRight(root, R);
            TrimLeft(root,L);
            return root;
        }
        
        public TreeNode findNewRoot(TreeNode root, int L, int R) {
            if (root.val >= L && root.val <= R)       return root;
            if (root.val < L)   return findNewRoot(root.right, L, R);
            return findNewRoot(root.left, L, R);
        }
        
        public void TrimRight(TreeNode root, int r) {
            TreeNode preRoot = root;
            while(root != null && root.val != r){
                if (root.val < r) {
                    preRoot = root;
                    root = root.right;
                } else {
                    root = root.left;
                    preRoot.right = root;
                }
            }
            if (root != null)        root.right = null;
        }
        
        public void TrimLeft(TreeNode root, int l) {
            TreeNode preRoot = root;
            while(root != null && root.val != l){
                if (root.val > l) {
                    preRoot = root;
                    root = root.left;
                } else {
                    root = root.right;
                    preRoot.left = root;
                }
            }
            if (root != null)        root.left = null;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.