Find Closest Value In BST

Prompt

Find Closest Value In BST
Write a function that takes in a Binary Search Tree (BST) and a target integer value and returns the closest value to that target value contained in the BST. You can assume that there will only be one closest value.
Each BST node has an integer value , a left child node, and a right child node. A node is said to be a valid BST
node if and only if it satises the BST property: its value is strictly greater than the values of every node to its left; its value is less than or equal to the values of every node to its right; and its children nodes are either valid BST nodes themselves or None / null .

Sample Input

ss

Sample Output

13

Solution 1

import java.util.*;

class Program {
  public static int findClosestValueInBst(BST tree, int target) {
    // Write your code here.
    return findClosestValueInBst(tree, target, Double.MAX_VALUE);//A
  }
	 public static int findClosestValueInBst(BST tree, int target, double closest) {
		 if (Math.abs(target - closest) > Math.abs(target - tree.value)){
			 closest = tree.value;
		 }
		 if (target < tree.value && tree.left != null){//B
			 return findClosestValueInBst(tree.left, target, closest);
		 } else if (target > tree.value && tree.right != null){
			 return findClosestValueInBst(tree.right, target, closest);
	 } else {
			 return (int)closest;
		 }
	 }

  static class BST {
    public int value;
    public BST left;
    public BST right;

    public BST(int value) {
      this.value = value;
    }
  }
}

# 1A

Integer.MAX_VALU;

这里不可以用int,因为有溢出问题
如果target是-1,tree.value有[1,2 ,2147483647],那么会返回2147483647
原码,补码和反码原理
原码,补码和反码原理补充

# 1B

细品

Solution 2

import java.util.*;

class Program {
  public static int findClosestValueInBst(BST tree, int target) {
    // Write your code here.
    return findClosestValueInBst(tree, target, Double.MAX_VALUE);
  }
	
	public static int findClosestValueInBst(BST tree, int target, double closest) {
		BST currentNode = tree;
		while (currentNode != null){
			if (Math.abs(closest - target) > Math.abs(currentNode.value - target)){
				closest = currentNode.value;
			}
			if (target < currentNode.value) {
				currentNode = currentNode.left;
			} else if (target > currentNode.value) {
				currentNode = currentNode.right;
			} else {
				break;
			}
		}
		return (int) closest;
	}

  static class BST {
    public int value;
    public BST left;
    public BST right;

    public BST(int value) {
      this.value = value;
    }
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值