LeetCode 669
题目:
解法: (递归)
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root == NULL) return NULL;
root ->left = trimBST(root -> left, low, high);
root -> right = trimBST(root -> right, low, high);
if(root -> val < low){
while(root -> right && root ->right -> val < low) root = root -> right;
return root -> right;
}
else if(root ->val == low){
root ->left = NULL;
return root;
}
if(root -> val > high){
while(root -> left && root ->left -> val > high) root = root -> left;
return root -> left;
}
else if(root ->val == high){
root -> right = NULL;
return root;
}
return root;
}
};
LeetCode108
解法:(递归)
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
int mid = nums.size()/2 ;
TreeNode* node = new TreeNode(nums[mid]);
vector<int> leftnums(nums.begin(),nums.begin() + mid);
vector<int> rightnums(nums.begin() + mid + 1,nums.end());
if(leftnums.size() > 0) node -> left = sortedArrayToBST(leftnums);
if(rightnums.size() > 0) node -> right = sortedArrayToBST(rightnums);
return node;
}
};
LeetCode538
题目:
解法:(递归)
class Solution {
public:
void buildBST(TreeNode* node ,int &val){
if(node == NULL) return;
buildBST(node ->right , val);
node ->val += val;
val = node -> val;
buildBST(node ->left,val);
}
TreeNode* convertBST(TreeNode* root) {
int val = 0;
buildBST(root, val);
return root;
}
};