Java Recursion easy


  • 0
    A

    Whenever the current node is in the range L and R move to the next left or right node....else if the current node is smaller than range L then move to the right subtree or else if the current node is greater than the R move to the left subtree

    class Solution {
        public TreeNode trimBST(TreeNode root, int L, int R) {
            
            if(root==null)
                return root;
        return solve(root,L,R);
            // return root;
        }
        
        TreeNode solve(TreeNode root, int L, int R)
        {
            if(root==null)
                return null;
                if(root.val>=L && root.val<=R)
                {
                  root.left=solve(root.left,L,R);
                   root.right=solve(root.right,L,R);
                }
            if(root.val<L){
    
                root=solve(root.right,L,R);
            }
            if(root!=null && root.val>R )
                root=solve(root.left,L,R);
            return root;
        }
    }

Log in to reply
 

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