Java Closest Binary Tree Value Solution, time complexity O(n), space complexity O(n).


  • 0
    V

    public class Solution {

    public int closestValue(TreeNode root, double target) {
        List<TreeNode> list = new ArrayList<TreeNode>();
        dfs(root, list);
        
        int len = list.size();
        int left = list.get(0).val;
        if(target <= left){
            return left;
        }
        for(int i = 1; i < len; i++){
            int right = list.get(i).val;
            if(left < target && target < right){
                double leftD = target - left;
                double rightD = right - target;
                return leftD > rightD ? right : left;
            }else if(target == right){
                return right;
            }
            left = right;
            
        }
        
        return left;
    }
    
    public void dfs(TreeNode root, List<TreeNode> list){
        if(root != null){
            dfs(root.left, list);
            list.add(root);
            dfs(root.right, list);
        }
    }
    

    }


Log in to reply
 

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