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.
解法1: Divide & Conquer
关于树的题目,先考虑试试分治的思想,对于一个root,要找出最接近他的数值,可能比他小也可能比他大。所以如果他本身不等于target的话需要比较left 和right。似乎分治行得通。
由于题目给出guarantee有一个解,则不需要考虑空树的情况。 那么只要分三种情况考虑:
- 左右子树都有, 那么比较左右子树的closestvalue和自身哪一个更close
- 左子树
- 右子树
其中2,3 只要比较root和其中一个子树算出来的结果就可以了。
C++
Java