递归
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == nullptr) {
return nullptr;
}
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
if (root->val < low) {
root = root->right;
} else if (root->val > high) {
root = root->left;
}
return root;
}
};
迭代
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (!root) {
return nullptr;
}
while (root && (root->val < low || root->val > high)) {
if (root->val < low) {
root = root->right;
} else {
root = root->left;
}
}
TreeNode* cur = root;
while (cur) {
while(cur->left && cur->left->val < low) {
cur->left = cur->left->right;
}
cur = cur->left;
}
cur = root;
while (cur) {
while(cur->right && cur->right->val > high) {
cur->right = cur->right->left;
}
cur = cur->right;
}
return root;
}
};
class Solution {
public:
TreeNode* traversal(vector<int>& nums, int start, int end) {
if (start == end) {
return nullptr;
}
//中点位置
int mid = start + (end - start) / 2;
TreeNode* root = new TreeNode(nums[mid]);
if (end - start == 1) {
return root;
}
root->left = traversal(nums, start, mid);
root->right = traversal(nums, mid + 1, end);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return traversal(nums, 0, nums.size());
}
};
自己实现版本(递归)
class Solution {
public:
int pre = 0;
TreeNode* convertBST(TreeNode* root) {
if (!root) {
return nullptr;
}
TreeNode* right = convertBST(root->right);
if (right && !pre){
pre = right->val;
}
root->val += pre;
pre = root->val;
convertBST(root->left);
return root;
}
};
精简版本
class Solution {
public:
int pre = 0;
void traversal(TreeNode* root) {
if (!root) {
return;
}
traversal(root->right);
root->val += pre;
pre = root->val;
traversal(root->left);
}
TreeNode* convertBST(TreeNode* root) {
traversal(root);
return root;
}
};
迭代
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
if(root == nullptr) {
return nullptr;
}
stack<TreeNode*> sta;
int pre = 0;
TreeNode* cur = root;
while (!sta.empty() || root) {
if (root) {
sta.push(root);
root = root->right;
}else {
root = sta.top();
root->val += pre;
pre = root->val;
sta.pop();
root = root->left;
}
}
return cur;
}
};