二叉搜索树中最接近的值——lintcode900

二叉搜索树中最接近的值

题目:二叉搜索树中最接近的值

给一棵非空二叉搜索树以及一个target值,找到在BST中最接近给定值的节点值

示例:

输入: root = {5,4,9,2,#,8,10} and target = 6.124780
输出: 5
解释:
二叉树 {5,4,9,2,#,8,10},表示如下的树结构:
        5
       / \
     4    9
    /    / \
   2    8  10

题解:分治法

方法1:递归实现

public class Solution {
    double minDValue;
    int result;
    public void dfs(TreeNode root, double target)
    {
        if(root==null) return;
        double divide=Math.abs(root.val-target);
        if(divide< minDValue){
            minDValue =divide;
            result=root.val;
        }
        if(target<root.val) dfs(root.left, target);
        else dfs(root.right, target);
    }
    public int closestValue(TreeNode root, double target) {
        minDValue=Double.MAX_VALUE;
        dfs(root, target);
        return result;
    }
}

方法2:非递归实现

public class Solution0 {

    public int closestValue(TreeNode root, double target) {
        double minDValue=Double.MAX_VALUE;
        int result=0;

        while (root!=null)
        {
            double divide=Math.abs(target-root.val);
            if(divide<minDValue){
                minDValue=divide;
                result=root.val;
            }
            if(target<root.val) {
                root=root.left;
            }else {
                root=root.right;
            }
        }
        return result;
    }
}
posted @ 2022-01-02 19:17  言思宁  阅读(55)  评论(0编辑  收藏  举报