1. 문제
2. 나의 풀이
2.1 in-order 리스트의 결과로 비교하기
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
print("root", root)
def in_order(node, result):
if node and node.left:
in_order(node.left, result)
if node:
result.append(node.val)
if node and node.right:
in_order(node.right, result)
return result
print("in_order", in_order(root, []))
in_order_list = in_order(root, [])
start_index = 0
end_index = len(in_order_list) - 1
while start_index < end_index:
if in_order_list[start_index] != in_order_list[end_index]:
return False
start_index += 1
end_index -= 1
return True
- input이
[1,2,2,2,null,2]
일 때, false여야 함-.-
2.2 in-order 리스트의 결과로 비교하기 + null인 노드고려하기
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
print("root", root)
def in_order(node, result):
if node and node.left:
in_order(node.left, result)
if node and node.left == None and node.right:
result.append(-1000)
if node:
result.append(node.val)
if node and node.right:
in_order(node.right, result)
if node and node.right == None and node.left:
result.append(-1000)
return result
print("in_order", in_order(root, []))
in_order_list = in_order(root, [])
start_index = 0
end_index = len(in_order_list) - 1
while start_index < end_index:
if in_order_list[start_index] != in_order_list[end_index]:
return False
start_index += 1
end_index -= 1
return True
- in_order가 대칭이어여도, tree가 identical하지 않은 케이스 발생
2-4. 왼쪽노드의 pre-order와 오른쪽 노드의 post-order의 reverse 값이 같으면 대칭임을 발견!
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def pre_order(node, result):
if node:
result.append(node.val)
if node and node.left:
in_order(node.left, result)
if node and node.left == None and node.right:
result.append(-1000)
if node and node.right:
in_order(node.right, result)
if node and node.right == None and node.left:
result.append(-1000)
return result
def in_order(node, result):
if node and node.left:
in_order(node.left, result)
if node and node.left == None and node.right:
result.append(-1000)
if node:
result.append(node.val)
if node and node.right:
in_order(node.right, result)
if node and node.right == None and node.left:
result.append(-1000)
return result
def post_order(node, result):
if node and node.left:
in_order(node.left, result)
if node and node.left == None and node.right:
result.append(-1000)
if node and node.right:
in_order(node.right, result)
if node and node.right == None and node.left:
result.append(-1000)
if node:
result.append(node.val)
return result
left = pre_order(root.left, [])
right = post_order(root.right, [])
right.reverse()
if left == right:
return True
return False
3. 남의 풀이