原创转载请注明出处:http://agilestyle.iteye.com/blog/2361956
Question:
Find the 'closest' value in a BST with a given value M
Analysis:
1. Traditional Binary Search Tree searching M: O(logN) time to return found M or not
2. "closest" value in BST to M: A particular value in the BST tree so that Math.abs(value-M) should be minimal
Solution:
1. Keep track of the whole searching path to find M and the diff between each value and M
2. Find the value where Math.abs(value-M) is minimal
3. Return min_diff+M as the returned value
package org.fool.java.test; public class FindClosestInBSTTest { public static void main(String[] args) { // 100 // 50 200 // 10 40 150 300 Tree myTree = new Tree(100); myTree.left = new Tree(50); myTree.right = new Tree(200); myTree.left.left = new Tree(10); myTree.left.right = new Tree(40); myTree.right.left = new Tree(150); myTree.right.right = new Tree(300); System.out.println(getCloset(myTree, 120)); System.out.println(getCloset(myTree, 80)); System.out.println(getCloset(myTree, 1000)); System.out.println(getCloset(myTree, 0)); } private static int getCloset(Tree t, int v) { return minDiff(t, v) + v; } private static int minDiff(Tree t, int v) { if (t == null) { return Integer.MAX_VALUE; } if (t.value < v) { return smallDiff(t.value - v, minDiff(t.right, v)); } else { return smallDiff(t.value - v, minDiff(t.left, v)); } } private static int smallDiff(int a, int b) { if (Math.abs(a) > Math.abs(b)) { return b; } return a; } private static class Tree { public int value; public Tree left; public Tree right; public Tree(int value) { this.value = value; this.left = null; this.right = null; } } }
Console Output
Reference
https://www.youtube.com/watch?v=NMdMIrHEA1E&index=37&list=PLlhDxqlV_-vkak9feCSrnjlrnzzzcopSG