Easy to follow Java recursive solution.


  • 3
    P
    public int closestValue(TreeNode root, double target) {
    		int temp = 0;
    		if (root.val > target && root.left != null) {
    			temp = closestValue(root.left, target); // go left.
    			return Math.abs(temp - target) > Math.abs(root.val - target) ? root.val : temp; // check condition.
    		} else if (root.right != null){
    			temp = closestValue(root.right, target); // go right
    			return Math.abs(temp - target) > Math.abs(root.val - target) ? root.val : temp;
    		}
    		else // both left and right child == null
    		    return root.val;
    
    	}
    

Log in to reply
 

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