leetcode解题: Closest Binary Search Tree Value (270)

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有一个解,则不需要考虑空树的情况。 那么只要分三种情况考虑:

  1. 左右子树都有, 那么比较左右子树的closestvalue和自身哪一个更close
  2. 左子树
  3. 右子树
    其中2,3 只要比较root和其中一个子树算出来的结果就可以了。

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int closestValue(TreeNode* root, double target) {
if (!root->left && !root->right) {
return root->val;
}
if (root->val == target) {
return target;
}
int child;
if (root->left && root->right) {
int left = closestValue(root->left, target);
int right = closestValue(root->right, target);
child = abs(left - target) <= abs(right - target)? left : right;
} else if (root->left) {
child = closestValue(root->left, target);
} else if (root->right) {
child = closestValue(root->right, target);
}
return abs(child - target) <= abs(root->val - target) ? child: root->val;
}
};

Java

1