代码随想录刷题随记20-二叉树9
669. 修剪二叉搜索树
leetcode链接
递归法
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root==nullptr)
return nullptr;
if(root->val<low)
return trimBST(root->right, low, high);
else if(root->val>high)
return trimBST(root->left, low, high);
else{
root->left=trimBST(root->left, low, high);
root->right=trimBST(root->right, low, high);
return root;
}
}
};
迭代法
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root==nullptr)
return root;
while(root!=nullptr&&((root->val<low)||(root->val>high))){
if(root->val<low)
root=root->right;
else
root=root->left;
}
if(root==nullptr)
return root;
TreeNode * cur=root;
//修建左树
while(cur!=nullptr){
while(cur->left!=nullptr&&cur->left->val<low){
cur->left=cur->left->right;
}
cur=cur->left;
}
cur=root;
//修剪右树
while(cur!=nullptr){
while(cur->right!=nullptr&&cur->right->val>high){
cur->right=cur->right->left;
}
cur=cur->right;
}
return root;
}
};
108.将有序数组转换为二叉搜索树
leetcode链接
这个思路比较简单,有点类似于二叉树重建
class Solution {
public:
TreeNode* sub(vector<int>& nums,int start,int end) {
if(end<start||end>=nums.size()||start<0)
return nullptr;
int len=end-start+1;
int bias=len/2;
int rootindex=start+bias;
TreeNode *root=new TreeNode(nums[rootindex]);
root->left=sub(nums, start, rootindex-1);
root->right=sub(nums,rootindex+1,end);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.size()==0)return nullptr;
return sub(nums,0,nums.size()-1);
}
};
538.把二叉搜索树转换为累加树
leetcode链接
可以利用二叉搜索树的有序性,中序遍历是从小到大,我们需要满足遍历到这个节点的时候,已经遍历过比这个节点大的节点,所以利用反中序遍历
解题代码:
递归法:
class Solution {
public:
void sub(TreeNode * root,int & pre){
if(root==nullptr)
return ;
sub(root->right,pre);
pre+=root->val;
root->val=pre;
sub(root->left,pre);
}
TreeNode* convertBST(TreeNode* root) {
int pre=0;
sub( root, pre) ;
return root;
}
};
迭代法
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
if(root==nullptr)
return nullptr;
TreeNode * cur=root;
stack<TreeNode *> mystack;
int pre=0;
while(cur!=nullptr||!mystack.empty()){
if(cur!=nullptr){
mystack.push(cur);
cur=cur->right;
}
else{
cur=mystack.top();
mystack.pop();
pre+=cur->val;
cur->val=pre;
cur=cur->left;
}
}
return root;
}
};