998. Maximum Binary Tree II

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]

Note:

1 <= B.length <= 100

方法1:recursion

思路:

和上一题654相比,这道题没有给max binary tree的原始数组nums,而是已经从654建好的tree root。那么已知新的数组是nums后面再加一个val,要返回modify过的新max binary tree。那么分为三种情况讨论,也就是example给出的三种:1. val > root ->val,新数字将成为新的根节点,root被连接到左边,因为顺序问题;2. val < root -> val,那么要遍历寻找该插入的位置,再一次,因为顺序问题,我们不考虑向左子树插入,只向右子树方向递归寻找这个再一次使val > root -> val满足的位置。如果没有找到,需要将新节点连成最后一个max的右紫薯;3. 如果找到了这样一个节点parent,那么它的右紫薯将被连接到新节点的左子树,而新节点被连到parent的右子树。

Complexity

Time complexity: O(h)
Space complexity: O(h)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* insertIntoMaxTree(TreeNode* root, int val) {
        TreeNode* node = new TreeNode(val);
        if (!root || root -> val < 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、付费专栏及课程。

余额充值