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要自己确定,一想这样算下来可不是个easy级别啊,那LR怎么确定呢?
实在是不理解就瞄了一眼solution,才恍然大悟L,R是给定的值。
递归用起来真的很爽气。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if(nullptr == root)
return nullptr;
if(root->val > R)
return trimBST(root->left, L, R);
if(root->val < L)
return trimBST(root->right, L, R);
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
}
};
运行结果,看来效率没那么好的。
Runtime: 28 ms, faster than 14.71% of C++ online submissions for Trim a Binary Search Tree.
Memory Usage: 23.7 MB, less than 5.26% of C++ online submissions for Trim a Binary Search Tree.
找个高人的算法如下,
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
/*
if(nullptr == root)
return nullptr;
if(root->val > R)
return trimBST(root->left, L, R);
if(root->val < L)
return trimBST(root->right, L, R);
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
*/
if(!root)
return nullptr;
root->left=trimBST(root->left,L,R);
root->right=trimBST(root->right,L,R);
return root->val<L?root->right:root->val>R?root->left:root;
}
};
看起来本质区别不大嘛,可是内存效率就好多了,其实两者各有千秋吧。
Runtime: 16 ms, faster than 95.51% of C++ online submissions for Trim a Binary Search Tree.
Memory Usage: 15 MB, less than 100.00% of C++ online submissions for Trim a Binary Search Tree.