Find the 'closest' value in a BST with a given value M

原创转载请注明出处: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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值