Leetcode - 106. Construct Binary Tree from Inorder and Postorder Traversal

숲사람·2022년 12월 28일
0

멘타트 훈련

목록 보기
198/237

문제

어떤 이진트리의 중위순회, 후외순회한 순서가 나열된 두 배열이 주어진다. 이것으로 원래 트리를 만들어라. (단 모든 값은 유니크한 수를 갖는다.)

Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]

아이디어

    [9,15,7,20,3] post
               ^
    [9,3,15,20,7] in
       ^
        node->left = gen_tree(in, post, left, pivot - 1, post_idx - (right - pivot + 1));
                                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        node->right = gen_tree(in, post, pivot + 1, right, post_idx - 1);
                                                           ^^^^^^^^^^^^

해결

class Solution {
    unordered_map<int, int> inidx;
public:

    TreeNode* gen_tree(vector<int> in, vector<int> post, int left, int right, int post_idx) {
        if (left > right)
            return NULL;
        // search post[post_idx] in in[]
        int pivot = inidx[post[post_idx]];
        TreeNode *node = new TreeNode;
        node->val = post[post_idx];
        node->left = gen_tree(in, post, left, pivot - 1, post_idx - (right - pivot + 1));
        node->right = gen_tree(in, post, pivot + 1, right, post_idx - 1);
        return node;
    }
    
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        for (int i = 0; i < inorder.size(); i++)
            inidx[inorder[i]] = i;
        return gen_tree(inorder, postorder, 0, inorder.size() - 1, postorder.size() - 1);
    }
};
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글