算法训练营day20_二叉树(2.29补)

算法训练营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);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值