转自:http://www.fgdsb.com/tags/BST/
k = 9
10
5
6
给一个target和一个BST, 写个算法找出离target最近的数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
TreeNode* closestBST(TreeNode* root,
int val){
if(!root)
return
nullptr;
if(root->val == val)
return root;
if(val < root->val){
if(!root->left)
return root;
TreeNode * p = closestBST(root->left, val);
return
abs(p->val-val) >
abs(root->val-val) ? root : p;
}
else {
if(!root->right)
return root;
TreeNode * p = closestBST(root->right, val);
return
abs(p->val-val) >
abs(root->val-val) ? root : p;
}
return
nullptr;
}
|