https://app.codesignal.com/interview-practice/task/tXN6wQsTknDT6bNrf/description
isTreeSymmetric | CodeSignal
// // Binary trees are already defined with this interface: // function Tree(x) { // this.value = x; // this.left = null; // this.right = null; // } function solution(t) { }
app.codesignal.com
✔️문제 요약
1.이진트리가 주어졌을 때, 좌우 대칭인지 아닌지 판별
✔️풀이 방법
1.좌우 반전된 순회를 돌려 같은지 다른지 판별함
2.난 이렇게 풀었지만 이 문제의 핵심은 안쪽과 바깥쪽을 나눠서 재귀를 통해 검사하는 것이 핵심인 문제이다 .
3.따라서 베스트 풀이는 재귀함수로 깊이를 파악하는 것이라고 함
# Binary trees are already defined with this interface:
# class Tree(object):
# def __init__(self, x):
# self.value = x
# self.left = None
# self.right = None
def solution(t):
if t == None:
return True
if t.left == None and t.right == None:
return True
currentleft = t.left
currentright = t.right
stack = [(currentleft,currentright)]
stack.pop()
while stack or currentleft or currentright:
if currentleft and currentright:
if currentleft.value != currentright.value:
return False
stack.append((currentleft,currentright))
currentleft=currentleft.left
currentright=currentright.right
elif currentleft and not currentright:
return False
elif currentright and not currentleft:
return False
else:
currentleft,currentright = stack.pop()
currentleft=currentleft.right
currentright=currentright.left
return True
✔️고찰
-베스트 풀이로는 못풀었지만 이걸 풀면서 스택,팝, 트리 구조에 대해 문법적으로 구현하지 못했던 것들이 한번에 이해돼서 너무 좋은 문제였다.
'코딩테스트 > 코딩테스트 Python' 카테고리의 다른 글
[프로그래머스] 구명보트(Python) (0) | 2023.04.06 |
---|---|
[CodeSignal] simplifyPath (Python) (0) | 2022.10.21 |
[CodeSignal] sudoku2 (Python) (1) | 2022.09.27 |
[CodeSignal] firstNotRepeatingCharacter (Python) (0) | 2022.09.19 |
[CodeSignal] findProfession (Python) (0) | 2022.09.19 |
댓글