티스토리 뷰
IT/Problem Solving
[C++] LeetCode : Construct Binary Tree from Preorder and Inorder Traversal
ROGERNM 2022. 8. 20. 23:26Question
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
이진 탐색 트리의 preorder 순서와 inorder순서로 탐색한 결과인 두 배열이 주어질 때, 원래의 이진트리를 출력하라.
제약사항
- 1 <= preorder.length <= 3000
- inorder.length == preorder.length
- -3000 <= preorder[i], inorder[i] <= 3000
- preorder and inorder consist of unique values.
- Each value of inorder also appears in preorder.
- preorder is guaranteed to be the preorder traversal of the tree.
- inorder is guaranteed to be the inorder traversal of the tree.
Solution
문제를 풀 때 고려한 사항
- 중복 원소가 있으면 풀이가 완전히 달라진다, 제약사항 확인이 필요하다.
- 빈 트리가 주어지는지 확인해야한다.
Solution1
preorder의 첫 번째 배열은 root노드이다.
inorder를 고려해보면 preorder에서 알아낸 root 노드의 양 옆은 각 왼쪽 서브 트리와 오른쪽 서브 트리이다.
class Solution {
public:
int preorder_index;
map<int, int> inorder_index;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
preorder_index = 0;
for(int i=0; i<inorder.size(); i++){
inorder_index[inorder[i]] = i;
}
return arrayToTree(preorder, 0, preorder.size() - 1);
}
TreeNode* arrayToTree(vector<int>& preorder, int left, int right){
if(left > right) return nullptr;
int root_val = preorder[preorder_index++];
TreeNode *root = new TreeNode(root_val);
root->left = arrayToTree(preorder, left, inorder_index[root_val]-1);
root->right = arrayToTree(preorder, inorder_index[root_val]+1, right);
return root;
}
};
- Time complexity : O(N)
- Space Complexity : O(N)
출처 : https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/788/
Explore - LeetCode
LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.
leetcode.com
'IT > Problem Solving' 카테고리의 다른 글
[C++] LeetCode : Kth Smallest Element in a BST (0) | 2022.08.20 |
---|---|
[C++] LeetCode : Populating Next Right Pointers in Each Node (0) | 2022.08.20 |
[C++] LeetCode : Binary Tree Zigzag Level Order Traversal (0) | 2022.08.20 |
[C++] LeetCode : Task Scheduler (0) | 2022.08.16 |
[C++] LeetCode : Majority Element (0) | 2022.08.16 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 인터뷰
- 러스트 기초
- 속초
- Tree
- 러스트 입문
- C++
- PS
- 자료구조
- Problem Solving
- 리트코드
- rust
- Interview
- 러스트
- ProblemSolving
- 내돈내산
- 트리
- algorithm
- LeetCode
- 반드시 알아야 할 자료구조
- DP
- Medium
- 기술면접
- 러스트 배우기
- interview question
- coding interview
- 알고리즘
- 속초 맛집
- 맛집
- 솔직후기
- 코딩인터뷰
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 28 |
글 보관함