998. Maximum Binary Tree II**

998. Maximum Binary Tree II**

https://leetcode.com/problems/maximum-binary-tree-ii/

题目描述

We are given the root node of a maximum tree: a tree where every node has a value greater than any other value in its subtree.

Just as in the previous problem(654. Maximum Binary Tree), the given tree was constructed from an list A (root = Construct(A)) recursively with the following Construct(A) routine:

  • If A is empty, return null.
  • Otherwise, let A[i] be the largest element of A. Create a root node with value A[i].
  • The left child of root will be Construct([A[0], A[1], ..., A[i-1]])
  • The right child of root will be Construct([A[i+1], A[i+2], ..., A[A.length - 1]])
  • Return root.

Note that we were not given A directly, only a root node root = Construct(A).

Suppose B is a copy of A with the value val appended to it. It is guaranteed that B has unique values.

Return Construct(B).

Example 1:

Input: root = [4,1,3,null,null,2], val = 5
Output: [5,4,null,1,3,null,null,2]
Explanation: A = [1,4,2,3], B = [1,4,2,3,5]

Example 2:

Input: root = [5,2,4,null,1], val = 3
Output: [5,2,4,null,1,null,3]
Explanation: A = [2,1,5,4], B = [2,1,5,4,3]

Example 3:

Input: root = [5,2,3,null,1], val = 4
Output: [5,2,4,null,1,3]
Explanation: A = [2,1,5,3], B = [2,1,5,3,4]

Note:

  • 1 <= B.length <= 100

C++ 实现 1

这道题前面的一大段描述, 都是在说 Maximum Binary Tree 是如何构建的, 构建方法其实在 654. Maximum Binary Tree** 中介绍了. 对于一个数组 A, 用其中的最大值 imax 来构建根节点, imax 左边的数构建左子树, imax 右边的数来构建右子树. 现在的问题是如果在原有的 A 末尾加上 val, 在原有基于 A 构建的树已经存在的情况下, 怎样将 val 插入到树中 ?

显然, 如果 val > root->val, 那就 val 就是最大值, 那么在数组 B 中, val 左边的数(即数组 A) 全部小于 val. 因此, 我们需要更新根节点, 用 val 来作为新的根节点, 然后将 A 构建的树作为新的根节点的左子树. 如果 val < root->val, 此时基于 A 构建的树的根节点不变, 由于 val 出现在 A 中最大值的右边, 所以需要插入到 A 的右子树.

class Solution {
public:
    TreeNode* insertIntoMaxTree(TreeNode* root, int val) {
        if (!root) return new TreeNode(val);
        if (val > root->val) {
            TreeNode *node = new TreeNode(val);
            node->left = root;
            return node;
        }
        root->right = insertIntoMaxTree(root->right, val);
        return root;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值