Home LeetCode - 998. Maximum Binary Tree II
Post
Cancel

LeetCode - 998. Maximum Binary Tree II

998. Maximum Binary Tree II - medium

문제

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).

제한사항

  • 1 <= B.length <= 100

입출력 예

exaple exaple

1
2
3
4
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]

exaple exaple

1
2
3
4
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]

exaple exaple

1
2
3
4
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]

풀이

  • Tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * 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) {
        // 현재 노드의 값보다 val의 값이 크거나,
        // 현재 노드의 값이 val값보다 작자는 뜻이 되므로 노드를 생성하여 교체
        // 또는 현재 노드가 마지막 리프 노드이라면, 
        // 마지막 리프노드를 새로 생성하여 기존 root에 붙임
        if(root == nullptr || val > root->val){
            auto node = new TreeNode(val);
            node->left = root;
            return node;
        }
        
        // 다음 right 노드를 탐색
        root->right = insertIntoMaxTree(root->right, val);
        return root;
    };
};
This post is licensed under CC BY 4.0 by the author.