最大二叉树
其实这题和用中序+后序构建二叉树是一样的。
找到最大值后将它的左右分为两个数组,然后分别放入root->left和root->right;
TreeNode* root;
if(nums.size()==0) return NULL;
int index=0;
int max=nums[0];
for(int i=1;i<nums.size();i++){
if(nums[i]>max){
max=nums[i];
index=i;
}
}
root=new TreeNode(max);
vector<int> left(nums.begin(),nums.begin()+index);
root->left=constructMaximumBinaryTree(left);
vector<int> right(nums.begin()+index+1,nums.end());
root->right=constructMaximumBinaryTree(right);
return root;
}
注意
如果一开始只是TreeNode* root;
没给它分配空间的话,后面需要用构造函数root=new TreeNode( max);
合并二叉树
题目
一开始我分为四种情况了:
1.终止 左右都为NULL return 空
2./3 有一边是空 ,另一边 不空,将不空的值赋给新树。
4.都不空,将和赋给新树。
但其实可以分的简单一点。
只要left==NULL return right;//剩下的树就和右边一样
right ==NULL return left;
这时因为前面的条件,再处理左右都不为空的情况
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(root1==NULL) return root2;
if(root2==NULL) return root1;
TreeNode* root=new TreeNode();
root->val=root1->val+root2->val;
root->left=mergeTrees(root1->left,root2->left);
root->right=mergeTrees(root1->right,root2->right);
return root;
}
二叉搜索树中的搜索
题目
其实就是二分查找的思想,root->val >目标值就找左边,<找右边
找到root==NULL 时说明找不到
验证二叉搜索树
题目
一开始我想的是只用验证root->left和root和root->right三个的值比较就好,但会有:
而用中序遍历二叉搜索树可以使其变为一个有序数组,可以用一个数组来记录,比较末尾和当前root
class Solution {
public:
TreeNode* pre;
bool isValidBST(TreeNode* root) {
if(root==NULL) return true;
bool l=isValidBST(root->left);
if(l==false)
return false;//及时返回
if(pre!=NULL&&pre->val>=root->val)
return false;//也可以用双指针来代替,它指向root的前一位
pre=root;
bool r=isValidBST(root->right);
if(r==false)
return false;
return l&&r;
}
};