Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 |
31 |
Tags
- serverless
- rds
- sns
- IaC
- aws
- amazonqcli
- cloudwatch
- lambda
- fcm
- 병목
- SageMaker
- CHECK
- Lamda
- kubernetes
- terraform
- Validation
Archives
- Today
- Total
잡다한 IT 지식
589. N-ary Tree Preorder Traversal 본문
본 알고리즘 풀이는 Routine Study에서 진행하고 있습니다.
저를 포함한 구성원이 대부분 초보이므로, 원하시는분은 언제라도 들어오셔도 좋습니다.
문의는 댓글 바람.
GitHub - ROUTINE-STUDY/Algorithm: 초보 알고리즘 스터디 / 누구나 참여 가능
초보 알고리즘 스터디 / 누구나 참여 가능 :runner:. Contribute to ROUTINE-STUDY/Algorithm development by creating an account on GitHub.
github.com
N-ary Tree Preorder Traversal - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
[문제 설명]
DFS로 왼쪽 깊은 순서부터 모든 요소 검색하기.
[처음 생각한 접근 방법]
그냥 단순한 DFS 구현문 같습니다. 단 스택에 넣을 때 왼쪽부터 넣으면
오른쪽부터 순서대로 나오게 되어서 FILO으로 인해 1,4,2,3,6,5 이런 식으로 나온다는 게 문제입니다.
이를 해결하기 위해 자식을 넣을 때 오른쪽부터 넣었습니다.
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> answer = new ArrayList<>();
Stack<Node> stack = new Stack<>();
if (root == null) return answer;
stack.push(root);
while (!stack.isEmpty()) {
Node temp = stack.pop();
answer.add(temp.val);
for (int i = temp.children.size() - 1; i >= 0; i--) {
stack.push(temp.children.get(i));
}
}
return answer;
}
}
'알고리즘 문제 풀이 > DFS' 카테고리의 다른 글
백준 - 점프왕 쩰리 (못풀었다가 검토하다 다시 품) (0) | 2021.12.26 |
---|---|
프로그래머스 - 타겟 넘버 (0) | 2021.08.11 |
100. Same Tree (0) | 2021.08.10 |
94. Binary Tree Inorder Traversal (0) | 2021.08.09 |
938.Range Sum of BST (0) | 2021.05.06 |