Java, Recursive Simple solution


  • 0
    S
    public class Solution {
        public int closestValue(TreeNode root, double target) {
            double diff = Math.abs(target-root.val);
            int potVal = root.val;
            if(root.val > target && root.left != null) {
               potVal = closestValue(root.left, target);
            }
            else if(root.val < target && root.right != null){
               potVal = closestValue(root.right, target); 
            }
            return diff > Math.abs(potVal-target)?potVal:root.val;
        }
    }

Log in to reply
 

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