Last active
September 3, 2017 17:12
-
-
Save cixuuz/a35d8dae151b77e7a82e0e9e3a78fbc8 to your computer and use it in GitHub Desktop.
[270. Closest Binary Search Tree Value] #leetcode
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
| // O(log(n)) O(1) | |
| class Solution { | |
| public int closestValue(TreeNode root, double target) { | |
| int a = root.val; | |
| TreeNode kid = target < a ? root.left : root.right; | |
| if (kid == null) return a; | |
| int b = closestValue(kid, target); | |
| return Math.abs(a - target) < Math.abs(b - target) ? a : b; | |
| } | |
| } | |
| class Solution1 { | |
| public int closestValue(TreeNode root, double target) { | |
| int closest = root.val; | |
| while (root != null) { | |
| if (Math.abs(closest - target) >= Math.abs(root.val - target)) { | |
| closest = root.val; | |
| } | |
| root = target < root.val ? root.left : root.right; | |
| } | |
| return closest; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment