[회고] 신입 iOS 개발자가 되기까지 feat. 카카오 자세히보기

💻 CS/알고리즘 연습

[알고리즘 연습] 길찾기 게임 (프로그래머스 lv3, 파이썬)

inu 2021. 7. 12. 23:43

문제

https://programmers.co.kr/learn/courses/30/lessons/42892

 

코딩테스트 연습 - 길 찾기 게임

[[5,3],[11,5],[13,3],[3,5],[6,1],[1,3],[8,6],[7,2],[2,2]] [[7,4,6,9,1,8,5,2,3],[9,6,5,8,1,4,3,2,7]]

programmers.co.kr

참고

https://inuplace.tistory.com/185?category=884573

 

[자료구조] 트리

트리란 상하 관계가 존재하는 자료구조이다. 링크드 리스트와 비슷하게 트리도 노드들을 가진다. 단, 각 노드는 데이터 정보뿐만 아니라, 자식에 대한 레퍼런스를 가진다. 이를 통해 계층적 구

inuplace.tistory.com

  • 트리 구조 및 순회에 대한 이해 필요

풀이

import sys sys.setrecursionlimit(10**6) class Tree: ​​​​def __init__(self,dataList): ​​​​​​​​self.data = max(dataList,key=lambda x :x[1]) ​​​​​​​​leftList =list(filter(lambda x :x[0] < self.data[0] , dataList)) ​​​​​​​​rightList = list(filter(lambda x :x[0] > self.data[0] , dataList)) ​​​​​​​​if leftList != []: ​​​​​​​​​​​​self.left=Tree(leftList) ​​​​​​​​else : ​​​​​​​​​​​​self.left=None ​​​​​​​​if rightList != []: ​​​​​​​​​​​​self.right=Tree(rightList) ​​​​​​​​else : ​​​​​​​​​​​​self.right=None def fix(node,preList,postList): ​​​​preList.append(node.data) ​​​​if node.left is not None: ​​​​​​​​fix(node.left,preList,postList) ​​​​if node.right is not None: ​​​​​​​​fix(node.right,preList,postList) ​​​​postList.append(node.data) def solution(nodeinfo): ​​​​answer = [] ​​​​root = Tree(nodeinfo) ​​​​postList = [] ​​​​preList = [] ​​​​fix(root,preList,postList) ​​​​answer.append(list(map(lambda x: nodeinfo.index(x)+1 ,preList))) ​​​​answer.append(list(map(lambda x: nodeinfo.index(x)+1 ,postList))) ​​​​return answer
  • 재귀를 이용해 트리를 초기화
  • 재귀를 이용해 트리 순회
  • 순회결과 도출