669. 修剪二叉搜索树
题目链接:https://leetcode.cn/problems/trim-a-binary-search-tree/submissions/
代码(递归):
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root == nullptr)
return root;
if(root->val < low)
{
TreeNode* right = trimBST(root->right,low,high);
return right;
}else if(root->val > high)
{
TreeNode* left = trimBST(root->left,low,high);
return left;
}
root->left = trimBST(root->left,low,high);
root->right = trimBST(root->right,low,high);
return root;
}
};
代码(迭代):
reeNode* trimBST(TreeNode* root, int low, int high) {
if(root == nullptr)
return root;
//重定位root
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;
}
};
注意13行和20行那里,要用while 而非if 否则
[3,1,4,null,2]
3
4
这个样例无法通过
108.将有序数组转换为二叉搜索树
题目链接:https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/submissions/
代码(递归):
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
int size = nums.size();
if(size == 0)
return nullptr;
int mid = size/2;
TreeNode* cur = new TreeNode(nums[mid]);
vector<int> left(nums.begin(),nums.begin() + mid);
vector<int> right(nums.begin() + mid +1 , nums.end());
cur->left = sortedArrayToBST(left);
cur->right = sortedArrayToBST(right);
return cur;
}
};
嘎嘎简单递归
迭代要用三个队列 溜了溜了
538.把二叉搜索树转换为累加树
题目链接:https://leetcode.cn/problems/convert-bst-to-greater-tree/submissions/
代码(迭代):
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
stack<TreeNode*> st;
if(root == nullptr)
return root;
TreeNode* tmp = root;
int pre = 0;
while(!st.empty() || tmp)
{
if(tmp)
{
st.push(tmp);
tmp = tmp->right;
}else
{
tmp = st.top();
st.pop();
tmp->val += pre;
pre = tmp->val;
tmp = tmp->left;
}
}
return root;
}
};
就是中序遍历 这都能忘
代码(递归):
class Solution {
public:
int pre = 0;
TreeNode* convertBST(TreeNode* root) {
valBST(root);
return root;
}
void valBST(TreeNode* root)
{
if(root == nullptr)
return;
valBST(root->right);
root->val += pre;
pre = root->val;
valBST(root->left);
return;
}
};