class Solution {
public:
TreeNode*judge(vector&nums,int left,int right){
if(left>=right) return nullptr;
//分割点下标
int maxNum=nums[left],index=left;//maxNum初始值为区间最左边的数
for(int i=left+1;imaxNum){
maxNum=nums[i];
index=i;
}
}
//cout< leftNums(nums.begin(),nums.begin()+index);
// vector rightNums(nums.begin()+index+1,nums.end());
root->left=judge(nums,left,index);
root->right=judge(nums,index+1,right);
return root;
}
TreeNode* constructMaximumBinaryTree(vector& nums) {
//思路二:不进行切割,直接在原数组上进行操作
return judge(nums,0,nums.size());
}
};
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
//思路:直接同时遍历两个二叉树,子节点不存在传入下一个为空指针
if(root1==nullptr) return root2;
if(root2==nullptr) return root1;
root1->val+=root2->val;
root1->left=mergeTrees(root1->left,root2->left);
root1->right=mergeTrees(root1->right,root2->right);
return root1;
}
};
思路:利用二叉搜索树的特性
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
//思路:找到节点,然后返回
//分析:左子节点比父节点小,右子节点比父节点大
if(root==nullptr)
return root;
TreeNode*newNode=root;;
if(newNode->val>val)
newNode=searchBST(newNode->left,val);
else if(newNode->valright,val);
return newNode;
}
};
class Solution {
public:
vectorans;
void judge(TreeNode*root){
if(root==nullptr) return;
judge(root->left);
ans.push_back(root->val);
judge(root->right);
}
bool isValidBST(TreeNode* root) {
//思路:直接分析
//思路二:中序遍历的数组一定递增
judge(root);
if(ans.size()==1) return true;
int pre=ans[0];
for(int i=1;i
class Solution {
public:
TreeNode*pre=nullptr;
bool isValidBST(TreeNode* root) {
if(root==nullptr) return true;//空树也是二叉搜索树
bool left=isValidBST(root->left);
if(pre!=nullptr && pre->val>=root->val) return false;//判断上一个节点是否小于当前节点
pre=root;
bool right=isValidBST(root->right);
return left && right;
}
};
class Solution {
public:
TreeNode*judgeNode(TreeNode*root,int low,int high){
if(root==nullptr) return root;
//分五种情况
TreeNode*left,*right;
if(root->valright,low,high);
else if(root->val>=low && root->val<=high){//左右两边都有可能在区间内
left=judgeNode(root->left,low,high);
right=judgeNode(root->right,low,high);
}
else if(root->val>high){
return judgeNode(root->left,low,high);
}
root->left=left;
root->right=right;
return root;
}
TreeNode* trimBST(TreeNode* root, int low, int high) {
//思路:首先考虑当前中间节点有三种情况,在low左边,在high右边
return judgeNode(root,low,high);
}
};
class Solution {
public:
TreeNode*judge(vector&nums,int left,int right){
if(left>right) return nullptr;
//每次都选择区间中间的数作为根节点
int mid=(left+right)/2;
TreeNode*root=new TreeNode(nums[mid]);
root->left=judge(nums,left,mid-1);
root->right=judge(nums,mid+1,right);
return root;
}
TreeNode* sortedArrayToBST(vector& nums) {
//思路一:高度平衡,递归切割
//后序遍历
return judge(nums,0,nums.size()-1);
}
};
class Solution {
public:
int sum=0;
TreeNode* convertBST(TreeNode* root) {
//思路:遍历顺序为右中左,然后累加赋值
if(root!=nullptr){
convertBST(root->right);
sum+=root->val;
root->val=sum;
convertBST(root->left);
}
return root;
}
};