모두CBT

다음 파이썬 프로그램의 실행 결과는?class NodeBS(object… | [7급 국가직 알고리즘] 26년 1회차 기출문제 상세 페이지

1[7급 국가직 알고리즘] 26년 1회차
다음 파이썬 프로그램의 실행 결과는?
class NodeBS(object):
def __init__(self, vl = None):
self.vl = vl
self.root = None
self.lf = None
self.rg = None
def _ad(self, vl):
nd = NodeBS(vl)
if vl > self.vl:
self.rg = self.rg and self.rg._ad(vl) or nd
elif vl < self.vl:
self.lf = self.lf and self.lf._ad(vl) or nd
else:
print("node duplicated")
return self
class Bst(NodeBS):
def add_node(self, vl):
if not self.root:
self.root = NodeBS(vl)
else:
self.root._ad(vl)
def order(self):
current = self.root
nodes, stack = [], []
while stack or current:
if current:
nodes.append(current.vl)
stack.append(current)
current = current.lf
else:
current = stack.pop()
current = current.rg
return nodes
if __name__ == "__main__":
bt = Bst()
in_list = [6, 4, 8, 2, 5, 7, 9, 1, 3, 10]
for i in in_list:
bt.add_node(i)
print(bt.order())
1
[6, 4, 2, 1, 3, 8, 5, 7, 9, 10]
2
[6, 4, 2, 1, 5, 8, 3, 7, 9, 10]
3
[6, 4, 2, 1, 3, 5, 8, 7, 9, 10]
4
[6, 4, 2, 1, 5, 3, 8, 7, 9, 10]
해설

프로그램은 이진 탐색 트리의 전위 순회 결과 [6, 4, 2, 1, 3, 5, 8, 7, 9, 10]을 출력한다.

삽입 결과 트리: 6의 왼쪽 4, 오른쪽 8 / 4의 왼쪽 2, 오른쪽 5 / 2의 왼쪽 1, 오른쪽 3 / 8의 왼쪽 7, 오른쪽 9 / 9의 오른쪽 10

order()는 노드를 방문하자마자 nodes에 추가하고 왼쪽으로 내려가며, 더 갈 곳이 없으면 스택에서 꺼낸 노드의 오른쪽으로 이동한다. 즉 루트 → 왼쪽 → 오른쪽 순서이다.
6 → 4 → 2 → 1 → 3 → 5 → 8 → 7 → 9 → 10

오류나 개정된 내용이 보이면 알려주세요

이어서 풀어보기

[7급 국가직 알고리즘] 26년 1회차 25문항 이어서 보기문제·정답·해설을 한 페이지에서 이어서 볼 수 있어요7급 국가직 알고리즘 기출문제 암기장 전체 보기