Given a non-empty binary search tree and a target value, find the value in the BST that's closest to the target.
Note:
- Given target value is a floating point.
- Guaranteed to has only one unique value in the BST, which is closest to the target.
Idea: recursive solution. Because it is a two-fork search tree, we do not need to traverse all the nodes to improve speed through prune.
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: A intClosestvalue (treenode* root,Doubletarget) { - intres = root->Val; - if(Root->left! = NULL && (Double) Res >target) { the intLeftres = Closestvalue (root->Left , target); -res = ABS (Res-target) < ABS (Leftres-target)?Res:leftres; - } - if(Root->right! = NULL && (Double) Res <target) { + intRightres = Closestvalue (root->Right , target); -res = ABS (Res-target) < ABS (Rightres-target)?Res:rightres; + } A returnRes; at } -};
Closest Binary Search Tree Value--Leetcode