本题我之前给想复杂了,其实非常的简单,就是道很简单的Easy题,
- 4比3.71大,所以不用看右边,目标只可能在root和左边,测一下Root对应的值
- 2比3.71小,所以不用看左边,目标只可能在当前的root和右边,测一下当前root对应的值
- 3比7小
所以:
- 时间复杂度:
- 空间复杂度:
代码如下:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/class Solution {public int closestValue(TreeNode root, double target) {if (root == null) {throw new IllegalArgumentException("Invalid Root");}int result = root.val;while (root != null) {double rootVal = (double)root.val;double minDiff = Math.abs((double)(result) - target);double diff = Math.abs(rootVal - target);if (diff < minDiff) {result = root.val;}if (rootVal < target) {// discard the left subtreeroot = root.right;}else {// discard the right subtreeroot = root.left;}}return result;}}
