您的位置:首页 > 其它

[Leetcode] 669. Trim a Binary Search Tree 解题报告

2018-01-29 12:43 519 查看
题目

Given a binary search tree and the lowest and highest boundaries as 
L
 and 
R
,
trim the tree so that all its elements lies in 
[L, R]
 (R >= L). You might need to change
the root of the tree, so the result should return the new root of the trimmed binary search tree.

Example 1:

Input:
1
/ \
0   2

L = 1
R = 2

Output:
1
\
2


Example 2:

Input:
3
/ \
0   4
\
2
/
1

L = 1
R = 3

Output:
3
/
2
/
1

思路

判断根节点的值和[L,R]的关系:如果比L还小,根节点也要被trim,所以返回对左子树的调用即可;如果比R还大,根节点同样要被trim,所以返回对右子树的调用即可。否则根节点就需要保留,所以我们分别trim其左右子树,然后返回根节点。

代码:/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) :
4000
val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if (root == NULL) {
return NULL;
}
if (root->val < L) {
return trimBST(root->right, L, R);
}
else if (root->val > R) {
return trimBST(root->left, L, R);
}
else {
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: