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, returnnull
. - Otherwise, let
A[i]
be the largest element ofA
. Create aroot
node with valueA[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:
Example 2:
Example 3:
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
的右子树.