### Problem Statement

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

**Note:**

- Given target value is a floating point.
- You are guaranteed to have only one unique value in the BST that is closest to the target.

**Example:**

Input:root = [4,2,5,1,3], target = 3.714286 4 / \ 2 5 / \ 1 3Output:4

Problem link

### Video Tutorial

You can find the detailed video tutorial here### Thought Process

This is a very easy problem as long as you are familiar with Binary Search Tree. In order to find the value that is closest to the given target, we can traverse the tree and keep a record of the minimum delta. Of course we can traverse the entire tree but we can definite do it better by always branch out either left or right given the target and root node value.For example, if current node is 10, and target is 9, the next possible smaller value must exist only on the left part of or with the current node

10 / \ 7 11

### Solutions

#### Recursion solution

#### Time Complexity: assuming tree size is N,O(lgN) since we are doing binary search

Space Complexity:O(1) if not considering recursion function stacks.

#### Iterative solution

```
public int closestValue(TreeNode root, double target) {
int ret = root.val;
while(root != null){
if(Math.abs(target - root.val) < Math.abs(target - ret)){
ret = root.val;
}
root = root.val > target? root.left: root.right;
}
return ret;
}
```

####
From:

https://leetcode.com/problems/closest-binary-search-tree-value/discuss/70331/Clean-and-concise-java-solution

Time Complexity: assuming tree size is N,O(lgN) since we are doing binary searchSpace Complexity:O(1)

## No comments:

## Post a Comment

Thank your for your comment! Check out us at https://baozitraining.org/ if you need mock interviews!