TRIM BST Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.
I am a newbie and just started learning recursion .. i wrote the code as written below . It works some some of the test cases and gives Null Pointer exception for the rest. I know the solution of the problem (also written below) but i want to fix my code instead of writing the way the solution is written.
here is my attempt.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode trimBST(TreeNode root, int L, int R) {
if(root==null)
{
return root;
}
if(root.val<L)
{
root=root.right;
if(root==null)
{
return root;
}
}
if(root.val>R)
{
root=root.left;
if(root==null)
{
return root;
}
}
if(root.left!=null)
{
if(root.left.val<L)
{
root.left=root.left.right;
}
}
if(root.right!=null)
{
if(root.right.val>R)
{
root.right=root.right.left;
}
}
trimBST(root.left,L,R);
trimBST(root.right,L,R);
return root;
}
}
gives error for
[3,1,4,null,2]
3
4
here is the solution
class Solution {
public TreeNode trimBST(TreeNode root, int L, int R) {
if (root == null) return root;
if (root.val > R) return trimBST(root.left, L, R);
if (root.val < L) return trimBST(root.right, L, R);
root.left = trimBST(root.left, L, R);
root.right = trimBST(root.right, L, R);
return root;
}
}
i know i have messed up somewhere in the recursion code and have made a value null and again using it and i feel that i am very close to the solution. I am not able to figure that out on my own. Please Help Me out.