[leetcode]669. Trim a Binary Search Tree
Analysis
ummmm~—— [ummmm~]
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.
参考了大神的做法:如果节点数值在范围内,则递归遍历其左子树和右子树;如果节点数值低于下界,则直接抛弃该节点和其左子树;如果节点数值高于上界,则直接抛弃该节点和其右子树。
Implement
/**
* 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:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if(!root)
return NULL;
if(root->val >= L && root->val <= R){
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
}
if(root->val < L)
return trimBST(root->right, L, R);
if(root->val > R)
return trimBST(root->left, L, R);
}
};