本题我之前给想复杂了,其实非常的简单,就是道很简单的Easy题,
    Image.jpeg

    1. 4比3.71大,所以不用看右边,目标只可能在root和左边,测一下Root对应的值
    2. 2比3.71小,所以不用看左边,目标只可能在当前的root和右边,测一下当前root对应的值
    3. 3比7小

    所以:

    • 时间复杂度:270. Closest Binary Search Tree Value - 图2
    • 空间复杂度: 270. Closest Binary Search Tree Value - 图3

    代码如下:

    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode() {}
    8. * TreeNode(int val) { this.val = val; }
    9. * TreeNode(int val, TreeNode left, TreeNode right) {
    10. * this.val = val;
    11. * this.left = left;
    12. * this.right = right;
    13. * }
    14. * }
    15. */
    16. class Solution {
    17. public int closestValue(TreeNode root, double target) {
    18. if (root == null) {
    19. throw new IllegalArgumentException("Invalid Root");
    20. }
    21. int result = root.val;
    22. while (root != null) {
    23. double rootVal = (double)root.val;
    24. double minDiff = Math.abs((double)(result) - target);
    25. double diff = Math.abs(rootVal - target);
    26. if (diff < minDiff) {
    27. result = root.val;
    28. }
    29. if (rootVal < target) {
    30. // discard the left subtree
    31. root = root.right;
    32. }
    33. else {
    34. // discard the right subtree
    35. root = root.left;
    36. }
    37. }
    38. return result;
    39. }
    40. }