Loading

leetcode-998. 最大二叉树 II

998. 最大二叉树 II

图床:blogimg/刷题记录/leetcode/998/

刷题代码汇总:https://www.cnblogs.com/geaming/p/16428234.html

题目

image-20220830174227121

思路

看到树就要想到递归。

解法

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* insertIntoMaxTree(TreeNode* root, int val) {
        if (root == nullptr || root->val < val) {
            return new TreeNode(val, root, nullptr);
        }
        root->right = insertIntoMaxTree(root->right, val);
        return root;
    }
};
  • 时间复杂度:\(O(n)\),最坏情况下,树呈现链状并且val最小,需要插入至最右边叶节点
  • 空间复杂度:\(O(1)\)

补充

posted @ 2022-08-30 18:51  Geaming  阅读(17)  评论(0编辑  收藏  举报