Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Leetcode 270. Closest Binary Search Tree Value
- Loading branch information
1 parent
a382940
commit 329721b
Showing
2 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package leetcode.LC_270; | ||
|
||
import base.TreeNode; | ||
|
||
/** | ||
* 270. Closest Binary Search Tree Value | ||
*/ | ||
class Solution270 { | ||
Integer candidate = null; | ||
Double minDiff = null; | ||
|
||
public int closestValue(TreeNode root, double target) { | ||
recur(root, target); | ||
return candidate; | ||
} | ||
|
||
private void recur(TreeNode node, final double target) { | ||
if (node == null) | ||
return; | ||
|
||
// Update candidate if diff smaller than minDiff | ||
double absDiff = Math.abs(node.val - target); | ||
if (minDiff == null || absDiff < minDiff) { | ||
candidate = node.val; | ||
minDiff = absDiff; | ||
} | ||
|
||
// Recursion w/ pruning | ||
if (target > node.val) { | ||
recur(node.right, target); | ||
} else { | ||
recur(node.left, target); | ||
} | ||
} | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package leetcode.LC_270; | ||
|
||
import base.TreeNode; | ||
import org.junit.Test; | ||
|
||
import static org.junit.Assert.*; | ||
|
||
public class Solution270Test { | ||
|
||
@Test | ||
public void closestValue_0() { | ||
TreeNode n1 = new TreeNode(0); | ||
assertEquals(0, new Solution270().closestValue(n1, 2147483648.0)); | ||
} | ||
|
||
@Test | ||
public void closestValue_1() { | ||
TreeNode n31 = new TreeNode(1); | ||
TreeNode n32 = new TreeNode(3); | ||
TreeNode n21 = new TreeNode(2); | ||
TreeNode n22 = new TreeNode(5); | ||
n21.left = n31; n21.right = n32; | ||
TreeNode n1 = new TreeNode(4); | ||
n1.left = n21; n1.right = n22; | ||
assertEquals(4, new Solution270().closestValue(n1, 3.714286)); | ||
} | ||
} |