Day20 二叉树第六天
LeetCode 654.最大二叉树
自己成功Debug出来了,递归构造最大二叉树。每次新构造二叉树时操作的是坐标。
提交出现了两次错误,一次是没有对L==R进行特判,导致函数会循环在这个范围内不断输出NULL,添加一个特判即可。
第二次是找最大值时没加等号,低级错误了。
class Solution {
public:
int findMax(vector<int>& nums,int l,int r){
int max=-1;
int index=0;
for(int i=l;i<=r;i++){
if(nums[i]>max){
max=nums[i];
index=i;
}
}
return index;
}
TreeNode* maxTree(vector<int>& nums,int l,int r){
if(l>r) return NULL;
if(l==r) return new TreeNode(nums[l]);
int base=findMax(nums,l,r);
TreeNode* root=new TreeNode(nums[base]);
root->left=maxTree(nums,l,base-1);
root->right=maxTree(nums,base+1,r);
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return maxTree(nums,0,nums.size()-1);
}
};
LeetCode 617.合并二叉树
一棵树独自遍历,两棵树就同步遍历。根据root2的情况修改root1的节点。
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(!root1) return root2;
if(!root2) return root1;
root1->val+=root2->val;
root1->left=mergeTrees(root1->left,root2->left);
root1->right=mergeTrees(root1->right,root2->right);
return root1;
}
};
LeetCode 700.二叉搜索树中的搜索
这才叫简单题!
来认识一下二叉搜索树。本题就利用二叉搜索树的特性就很简单。
解法1:递归法
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(!root || root->val==val) return root;
if(root->val>val) return searchBST(root->left,val);
if(root->val<val) return searchBST(root->right,val);
return NULL;
}
};
解法2:迭代法
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while(root){
if(root->val>val) root=root->left;
else if(root->val<val) root=root->right;
else return root;
}
return NULL;
}
};
递归和迭代都如此简单,这就是二叉搜索树的魅力。
LeetCode 98.验证二叉搜索树
验证二叉搜索树就是中序遍历二叉树,看产生的序列是不是有序的,这就是二叉搜索树的特征。
与数组判断是否递增类似,我们也可以在二叉树上逐步判断每次中序遍历的下一个节点是不是比上一个节点大,只要前一节点大于等于当前节点就直接返回false。
class Solution {
public:
TreeNode* pre=NULL;
bool isValidBST(TreeNode* root) {
if(!root) return true;
bool left=isValidBST(root->left);
if(pre && pre->val>=root->val) return false;
pre=root;
bool right=isValidBST(root->right);
return left && right;
}
};
二叉树递归,渐入佳境!