代码随想录训练营第二十天|654.最大二叉树、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树

654.最大二叉树

链接:LeetCode654.最大二叉树
思路:
从头到尾遍历给定的数组,找出其中最大的元素所在的下标index.依据最大的数值建立节点。按照index,将区间一分为二进行递归。

class Solution {
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        return construct(nums,0,nums.size()-1);
    }
private:
    //确定递归参数和返回值
    TreeNode* construct(vector<int>&nums,int st,int en){
        if(st>en) return nullptr;
        int maxindex = st;
        for(int i=st+1;i<=en;++i) if(nums[i]>nums[maxindex]) maxindex=i;
        TreeNode *node = new TreeNode(nums[maxindex]);
        node->left = construct(nums,st,maxindex-1);
        node->right = construct(nums,maxindex+1,en);
        return node;
    }
};

617.合并二叉树

链接:LeetCode617.合并二叉树
将root2合并在root1中,并返回root1的根节点。

class Solution {
public:
    //将root2合并在root1中
    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
        //递归终止边界
        if(!root1) return root2;
        else if(!root2) return root1;
        //单层处理逻辑,前序遍历
        root1->val += root2->val;
        root1->left = mergeTrees(root1->left,root2->left);
        root1->right = mergeTrees(root1->right,root2->right);

        return root1;
    }
};

700.二叉搜索树中的搜索

链接:LeetCode700.二叉搜索树中的搜索
利用二叉搜索树中序遍历的有序性,在树上进行二分查找。

class Solution {
public:
    TreeNode* searchBST(TreeNode* root, int val) {
        //递归终止边界
        if(!root) return root;

        //单层递归逻辑(二分查找)
        if(root->val == val) return root;
        else if(root->val > val) return searchBST(root->left,val);
        return searchBST(root->right,val);


    }
};

98.验证二叉搜索树

链接:LeetCode98.验证二叉搜索树
利用二叉搜索树中序遍历的有序性,对树进行遍历和判断。
主要判断方式:前一个遍历的节点的值小于当前节点的值。
所以需要用一个变量记录上一个节点。

class Solution {
public:
    TreeNode *pre = nullptr;
    bool isValidBST(TreeNode* root) {
        if(root->left&&!isValidBST(root->left)) return false;
        if(pre&& pre->val>= root->val) return false;
        pre = root;
        if(root->right&&!isValidBST(root->right)) return false;
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值