算法训练营day20_二叉树(2.29补)
654.最大二叉树
从数组中找到最大值,作为当前节点的下标;
递归构造左子树,递归构造右子树;
前序遍历;
class Solution {
public:
TreeNode* dfs(vector<int> nums,int l,int r){
if(l>r) return NULL;
TreeNode *t=new TreeNode();
int maxIndex=l;
for(int i=l;i<=r;i++){
if(nums[i]>=nums[maxIndex]) maxIndex=i;
}
t->val=nums[maxIndex];
t->left=dfs(nums,l,maxIndex-1);
t->right=dfs(nums,maxIndex+1,r);
return t;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return dfs(nums,0,nums.size()-1);
}
};
617.合并二叉树
两个都空返回空;
t1空返回t2;t2空返回t1;
都不空返回加和,往下左右子树;
class Solution {
public:
TreeNode* dfs(TreeNode* root1,TreeNode* root2){
if(root1==NULL&&root2==NULL) return NULL;
if(root1==NULL) return root2;
if(root2==NULL) return root1;
TreeNode* root=new TreeNode(0);
root->val=root1->val+root2->val;
root->left=dfs(root1->left,root2->left);
root->right=dfs(root1->right,root2->right);
return root;
}
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
return dfs(root1,root2);
}
};
700.二叉搜索树中的搜索
当前点是目标节点,就传上去;
否则就往左右儿子走,若左右儿子能返回上来目标目标节点,传上去;不能就传NULL;
class Solution {
public:
TreeNode* dfs(TreeNode* t,int val){
if(t==NULL) return NULL;
if(t->val==val) return t;
TreeNode* t1=dfs(t->left,val);
TreeNode* t2=dfs(t->right,val);
if(t1!=NULL&&t1->val==val) return t1;
if(t2!=NULL&&t2->val==val) return t2;
return NULL;
}
TreeNode* searchBST(TreeNode* root, int val) {
return dfs(root,val);
}
};
98.验证二叉搜索树
二叉搜索树中序遍历是递增序列;
中序遍历,pre存上一个点的值;
先dfs左子树,然后比较中点与pre的值,然后dfs右子树;
const long long INX=1e12;
class Solution {
public:
long long pre=-INX;
bool dfs(TreeNode* t){
if(t==NULL) return true;
if(!dfs(t->left)) return false;
if(t->val<=pre) return false;
pre=t->val;
return dfs(t->right);
}
bool isValidBST(TreeNode* root) {
return dfs(root);
}
};