Closet value for all binary tree Java recursive solution


  • 0
    Z
    public int closestValue(TreeNode root, double target) {
    	List<Integer> list = new ArrayList<>();
    	closestValue(root, target,list);
    	return list.get(0);
    }
    
    public void closestValue(TreeNode root, double target, List<Integer> list){
    	if (root.left != null) {
    		closestValue(root.left, target, list);
    	}
    	if (root.right != null) {
    		closestValue(root.right, target, list);
    	}
    	double rest =   Math.abs(target - root.val);
    	if (list.size() == 0) {
    		list.add(root.val);
    	}
    	
    	if ( Math.abs(list.get(0)-target) > rest) {
    		list.set(0, root.val);
    	}
    		 
    	
    }

Log in to reply
 

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