Monday, November 2, 2015

[leetcode]Closest Binary Search Tree Value

The solution can be pruned.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    double maxDiff = Double.MAX_VALUE;
    int value = -1;
    public int closestValue(TreeNode root, double target) {
        findClose(root, target);
        return value;
    }

    private void findClose(TreeNode root, double target){
        if (root == null) return;
        if (maxDiff > Math.abs((double)root.val-target)){
            maxDiff = Math.abs(root.val-target);
            value = root.val;
        }
        findClose(root.left, target);
        findClose(root.right, target);
    }
}

No comments:

Post a Comment