题目669
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root ==NULL) return NULL;
if(root->val>high) return trimBST(root->left,low,high);
if(root->val<low) return trimBST(root->right,low,high);
root->left=trimBST(root->left,low,high);
root->right= trimBST(root->right,low,high);
return root;
}
};
题目:104
class Solution {
private:
TreeNode *travseal(vector& num,int left,int right){
if(left>right) return nullptr;
int mid=left+(right-left)/2;
TreeNode root= new TreeNode(num[mid]);
root->left=travseal(num,left,mid-1);
root->right=travseal(num,mid+1,right);
return root;
}
public:
TreeNode sortedArrayToBST(vector& num) {
TreeNode *root=travseal(num,0,num.size()-1);
return root;
}
};
题目 538
class Solution {
private:
int pre = 0; // 记录前一个节点的数值
void traversal(TreeNode* cur) { // 右中左遍历
if (cur == NULL) return;
traversal(cur->right);
cur->val += pre;
pre = cur->val;
traversal(cur->left);
}
public:
TreeNode* convertBST(TreeNode* root) {
pre = 0;
traversal(root);
return root;
}
};