Skip to content

Commit

Permalink
Add Leetcode 270. Closest Binary Search Tree Value
Browse files Browse the repository at this point in the history
  • Loading branch information
naco-siren committed May 10, 2020
1 parent a382940 commit 329721b
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/leetcode/LC_270/Solution270.java
@@ -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);
}
}
}
27 changes: 27 additions & 0 deletions src/leetcode/LC_270/Solution270Test.java
@@ -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));
}
}

0 comments on commit 329721b

Please sign in to comment.