998. 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, 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]

Constraints:

  • 1 <= B.length <= 100

这道题完全是基于之前那道 Maximum Binary Tree 出的,没做上面这道就不太好理解这道题的意思,简单说一下,之前那道题就是给了一个数组,然后用其中最大的值当作根结点,且左边的子数组递归生成左子树,右边的子数组递归生成右子树。而这道题没有给初始数组,而是给了一个已经按这种方式生成的二叉树,然后说是在生成该二叉树的原数组的后面加上一个数字 val,让返回生成新的二叉树。最笨的方法就是先根据二叉树还原出原数组,然后在加上 val,再次调用 Maximum Binary Tree 中的方法生成的新的二叉树。这种方法可以通过 OJ,但是感觉不太聪明的样子,其实这道题有很简洁的解法,几行就搞定了。由于新的数字 val 一定是加在数组的末尾的,其在数组中的大小关系就变的很重要了,由于数组中的最大值将作为根结点,若 val 是最大值,则其一定是新的根结点,原二叉树直接变成其左子树了,直接就得到了结果。若 val 小于当前数组的最大值,则其一定是在右子树中,则可以对最大值右边的子数组调用递归函数,即对根结点的右子结点调用递归函数,将返回的结点更新为新的右子结点即可,参见代码如下:

class Solution {
public:
    TreeNode* insertIntoMaxTree(TreeNode* root, int val) {
        if (root && root->val > val) {
            root->right = insertIntoMaxTree(root->right, val);
            return root;
        }
        return new TreeNode(val, root, nullptr);
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/998

类似题目:

Maximum Binary Tree

参考资料:

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

https://leetcode.com/problems/maximum-binary-tree-ii/discuss/242897/Java-clean-recursive-solution

https://leetcode.com/problems/maximum-binary-tree-ii/discuss/242936/JavaC%2B%2BPython-Recursion-and-Iteration

LeetCode All in One 题目讲解汇总(持续更新中…)


转载请注明来源于 Grandyang 的博客 (grandyang.com),欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 grandyang@qq.com

💰


微信打赏


Venmo 打赏

×

Help us with donation