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:


998. Maximum Binary Tree II**_算法

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:


998. Maximum Binary Tree II**_算法_02

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:


998. Maximum Binary Tree II**_c++_03

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;
}
};