算法训练营第二十二天 | LeetCode 654 最大二叉树、LeetCode 617 合并二叉树、LeetCode 700 二叉搜索树中的搜索、LeetCode 98 验证二叉搜索树

LeetCode 654 最大二叉树

和昨天的中序、后序遍历构建二叉树很像,只是昨天需要注释掉的地方,今天注释掉会报错,需要加上去了。

class Solution {
public:
    TreeNode* mybuildTree(vector<int>& nums, int l, int r) {
        if (l > r) return nullptr;
        if (l == r) {
            TreeNode* cur = new TreeNode(nums[l]);
            return cur;
        }
        int maxNum = 0;
        int maxIndex = 0;
        for (int i = l; i <= r; i++) {
            if (maxNum < nums[i]) {
                maxNum = nums[i];
                maxIndex = i;
            }
        }
        TreeNode* cur = new TreeNode(maxNum);
        cur->left = mybuildTree(nums, l, maxIndex - 1);
        cur->right = mybuildTree(nums, maxIndex + 1, r);
        return cur;
    }
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        return mybuildTree(nums, 0, nums.size() - 1);
    }
};

LeetCode 617 合并二叉树

用递归也是一样很容易做

class Solution {
public:
    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
        if (!root1 && !root2) return root1;
        if (root1 && !root2) return root1;
        if (!root1 && root2) return root2;
        TreeNode* cur = new TreeNode(root1->val + root2->val);
        cur->left = mergeTrees(root1->left, root2->left);
        cur->right = mergeTrees(root1->right, root2->right);
        return cur;
    }
};

这题迭代法暂时还不会写,后面需要加强。

LeetCode 700 二叉搜索树中的搜索

这题首先是二叉搜索树,要比较大小直接用一个cur指针进行类似二分查找的操作就行了

代码如下:

class Solution {
public:
    TreeNode* searchBST(TreeNode* root, int val) {
        TreeNode* cur = root;
        while (cur && cur->val != val) {
            if (cur->val < val) cur = cur->right;
            else if (cur->val > val) cur = cur->left;
        }
        return cur;
    }
};

LeetCode 98 验证二叉搜索树

这题其实不是很难,将二叉搜索树按中序遍历遍历一遍后看数组是否严格递增就行了。只是我在写中序遍历的时候,把它和层序遍历用的队列弄混了,断点打了好几次,还是没找出来,最后一拍脑门才发现这个错误,读者要引以为戒啊!

代码如下:

class Solution {
public:
    bool isValidBST(TreeNode* root) {
        TreeNode* cur = root;
        stack<TreeNode*> mysta;
        vector<int> inorder;
        while (cur || !mysta.empty()) {
            while (cur) {
                mysta.push(cur);
                cur = cur->left;
            }
            cur = mysta.top();
            mysta.pop();
            inorder.push_back(cur->val);
            cur = cur->right;
        }
        for (int i = 0; i < inorder.size() - 1; i++) {
            if (inorder[i + 1] <= inorder[i]) return false;
        }
        return true;
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值