Created
April 27, 2019 19:14
-
-
Save shixiaoyu/afb93a8200f80695c9c5498d0b1e9dd0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private double curMinDelta = Double.MAX_VALUE; | |
private int smallestValue = 0; | |
public int closestValue(TreeNode root, double target) { | |
this.searchMin(root, target); | |
return this.smallestValue; | |
} | |
private void searchMin(TreeNode root, double target) { | |
if (root == null) { | |
return; | |
} | |
if (target == root.val) { | |
this.smallestValue = root.val; | |
return; | |
} | |
double delta = Math.abs(target - root.val); | |
if (delta < this.curMinDelta) { | |
smallestValue = root.val; | |
this.curMinDelta = delta; | |
} | |
if (target < root.val) { | |
this.searchMin(root.left, target); | |
} else { | |
this.searchMin(root.right, target); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment