티스토리 뷰
이진트리에서 순회하는 종류는 세 가지가 있다.
루트 노드를 기준으로 루트 노드 - 왼쪽 자식 트리 - 오른쪽 자식 트리를 순차적으로 방문하는 전위 순회,
왼쪽 자식 트리 - 루트 노드 - 오른쪽 자식 트리를 순차적으로 방문하는 중위 순회,
그리고 마지막으로 왼쪽 자식 트리 - 오른쪽 자식 트리 - 루트 노드를 방문하는 후위 순회다.
재귀함수 심화 대표 문제인 하노이탑 이동 순서처럼, 방문하는 순서에 맞게 재귀를 돌려주고 그 안에서 루트 노드를 로그 프린팅 하며 원하는 답을 출력할 수 있다.
nodes = dict()
for _ in range(int(input())):
root, left, right = map(str, input().split())
nodes[root] = [left, right]
# 전위 순회
def printPreorder(root):
# 루트
print(root, end= "")
if nodes[root] == ['.', '.']:
return
# 왼쪽
if nodes[root][0] != '.':
printPreorder(nodes[root][0])
# 오른쪽
if nodes[root][1] != '.':
printPreorder(nodes[root][1])
# 중위 순회
def printInorder(root):
# 왼쪽
if nodes[root][0] != '.':
printInorder(nodes[root][0])
# 루트
print(root, end= "")
if nodes[root] == ['.', '.']:
return
# 오른쪽
if nodes[root][1] != '.':
printInorder(nodes[root][1])
# 후위 순회
def printPostorder(root):
# 왼쪽
if nodes[root][0] != '.':
printPostorder(nodes[root][0])
# 오른쪽
if nodes[root][1] != '.':
printPostorder(nodes[root][1])
# 루트
print(root, end="")
if nodes[root] == ['.', '.']:
return
printPreorder('A')
printInorder('A')
printPostorder('A')
'PS (Problem Solving)' 카테고리의 다른 글
[BOJ, Python] 14915 - 진수 변환기 (0) | 2023.01.28 |
---|---|
[BOJ, Python] 2293 - 동전 1 ( with Recursion, DP ) (0) | 2023.01.10 |
[BOJ, Python] 1644 - 소수의 연속합 ( with 에라토스테네스의 체, 투 포인터 ) (0) | 2023.01.08 |
[BOJ, Python] 11401 - 이항 계수 3 ( with Fermat's little theorem ) (1) | 2022.12.14 |
[BOJ, Python] 17626 - Four Squares ( with DP ) (0) | 2022.11.23 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 하노이탑이동순서
- 곱셈의 역원
- how to remove border of tabbarcontroller
- 백준
- BOJ
- DFS
- xcode
- Javascript
- DP
- c++
- swift
- Python
- 파이썬
- ios
- TIP
- SVG
- HTML
- 정보시각화
- D3
- pyrebase
- 백트래킹
- PS
- SceneDelegate
- 보라매사옥
- 알고리즘
- Array
- CSS
- 자료구조
- how to start without storyboard
- CSV
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함