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

本文介绍了一种在二叉搜索树(BST)中查找最接近给定值M的方法。通过递归遍历BST并记录与M差值最小的节点来实现。文章提供了完整的Java代码示例及运行结果。

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

 

以下是 NumPy 编程题第 46、50~54 题的详细解答与代码示例。 --- ### ✅ **46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area (★★☆)** #### ✅ 示例代码: ```python import numpy as np # 创建一个 10x10 的结构化数组,表示 [0,1]x[0,1] 上的点 x = np.linspace(0, 1, 10) y = np.linspace(0, 1, 10) X, Y = np.meshgrid(x, y) # 定义结构化数据类型 dtype = [('x', float), ('y', float)] # 创建结构化数组 Z = np.empty(X.shape, dtype=dtype) Z['x'] = X Z['y'] = Y print(Z) ``` #### ✅ 解释: - 使用 `np.meshgrid` 生成网格坐标; - 使用结构化 `dtype` 来表示每个点的 `(x, y)`; - 最终 `Z` 是一个结构化数组,每个元素都有 `x` 和 `y` 字段。 --- ### ✅ **50. How to find the closest value (to a given scalar) in a vector? (★★☆)** #### ✅ 示例代码: ```python import numpy as np Z = np.random.random(10) value = 0.5 # 找到最接近 value 的元素 closest = Z[np.abs(Z - value).argmin()] print("Vector:", Z) print("Closest to", value, "is:", closest) ``` #### ✅ 解释: - `np.abs(Z - value)` 计算每个元素与目标值的差; - `.argmin()` 找到最小差值的位置; - 即为最接近的值。 --- ### ✅ **51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)** #### ✅ 示例代码: ```python import numpy as np dtype = [('position', [('x', float), ('y', float)]), ('color', [('r', float), ('g', float), ('b', float)])] Z = np.zeros(5, dtype=dtype) # 设置第一个元素的值 Z[0] = ((1.0, 2.0), (0.5, 0.5, 0.5)) print(Z) ``` #### ✅ 解释: - 使用嵌套的结构化 `dtype` 表示位置和颜色; - 每个元素是一个结构体,包含 position 和 color。 --- ### ✅ **52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)** #### ✅ 示例代码: ```python import numpy as np # 创建 100 个点 (x, y) points = np.random.rand(100, 2) # 计算每对点之间的欧几里得距离 diff = points[:, np.newaxis, :] - points[np.newaxis, :, :] distances = np.sqrt(np.sum(diff**2, axis=-1)) print("Distance matrix shape:", distances.shape) ``` #### ✅ 解释: - 使用广播机制计算每对点之间的差; - `np.newaxis` 用于扩展维度; - 最终得到一个 `100x100` 的距离矩阵。 --- ### ✅ **53. How to convert a float (32 bits) array into an integer (32 bits) in place?** #### ✅ 示例代码: ```python import numpy as np Z = np.arange(10, dtype=np.float32) print("Before conversion:", Z.dtype) # 原地转换类型为 int32(共享内存) Z32 = Z.view(np.int32) # 注意:这只是解释内存中数据的方式,并不改变原始值 print("After view as int32:", Z32) ``` #### ✅ 解释: - `view()` 用于原地改变解释方式(不复制数据); - 注意:这不会进行真正的类型转换(不改变内存中的二进制表示); - 如果你希望**真正转换数值类型**,应使用 `.astype(np.int32)`; - `view()` 可用于查看内存布局,但要谨慎使用。 --- ### ✅ **54. How to read the following file? (★★☆)** ``` 1, 2, 3, 4, 5 6, , , 7, 8 , , 9,10,11 ``` #### ✅ 示例代码: ```python import numpy as np from io import StringIO # 模拟文件内容 data = StringIO('''1, 2, 3, 4, 5 6, , , 7, 8 , , 9,10,11''') # 读取并自动处理缺失值 Z = np.genfromtxt(data, delimiter=",", dtype=float) print(Z) ``` #### ✅ 输出: ``` [[ 1. 2. 3. 4. 5.] [ 6. nan nan 7. 8.] [nan nan 9. 10. 11.]] ``` #### ✅ 解释: - `np.genfromtxt()` 支持读取带缺失值的 CSV; - 自动将空值转换为 `nan`; - 使用 `StringIO` 模拟文件输入。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值