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, returnnull
. - Otherwise, let
A[i]
be the largest element ofA
. Create aroot
node with valueA[i]
. - The left child of
root
will beConstruct([A[0], A[1], ..., A[i-1]])
- The right child of
root
will beConstruct([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
Solution: Recursion
Since val is the last element of the array, we compare root->val with val, if root->val > val then val can be inserted into the right subtree recursively, otherwise, root will be the left subtree of val.
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 |
class Solution { public: TreeNode* insertIntoMaxTree(TreeNode* root, int val) { if (root && root->val > val) { root->right = insertIntoMaxTree(root->right, val); return root; } auto node = new TreeNode(val); node->left = root; return node; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment