0
点赞
收藏
分享

微信扫一扫

如何找到更多音视频开发学习资料和资源?

潇湘落木life 2023-06-28 阅读 27

Day 20 二叉树

654. 最大二叉树

递归

class Solution {
    TreeNode *build(const vector<int> &nums, int left, int right)
    {
        if (left >= right) return nullptr;
        int idx = left;
        for (int i = left + 1; i < right; ++i) 
        {
            if (nums[i] > nums[idx])
            {
                idx = i;
            }
        }
        TreeNode *root = new TreeNode(nums[idx]);
        root->left = build(nums, left, idx);
        root->right = build(nums, idx + 1, right);
        return root;
    }

public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        return build(nums, 0, nums.size());
    }
};

迭代

待补充

617. 合并二叉树

递归

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

迭代

待补充

700. 二叉搜索树中的搜索

递归

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

迭代

class Solution {
public:
    TreeNode* searchBST(TreeNode* root, int val) {
        TreeNode *cur = root;

        while (cur)
        {
            if (cur->val > val)
            {
                cur = cur->left;
            }
            else if (cur->val < val)
            {
                cur = cur->right;
            }
            else
            {
                return cur;
            }
        }

        return nullptr;
    }
};

98. 验证二叉搜索树

遇到两个坑的地方:

  1. 递归的时候,不能光验证左子树的根节点小于当前根节点,右子树的根节点大于但当前根节点,别忘了左子树上的每一个节点都要求比根节点要小,右子树上的每一个节点都要求比根节点大。
  2. 根节点跟左(右)子树中的某一个节点相等,也是不符合二叉搜索树的规则的

递归

待补充

迭代

class Solution {
public:
    bool isValidBST(TreeNode* root) {
        stack<TreeNode*> stk;
        vector<int> table;

        TreeNode *cur = root;
        while (cur || !stk.empty())
        {
            if (cur)
            {
                stk.push(cur);
                cur = cur->left;
            }
            else
            {
                cur = stk.top();
                stk.pop();
                table.push_back(cur->val);
                cur = cur->right;
            }
        }

        for (int i = 1; i < table.size(); ++i)
        {
            if (table[i] <= table[i - 1])
            {
                return false;
            }
        }

        return true;
    }
};
举报

相关推荐

0 条评论