Python/PS in Python
LeetCode 101. Symmetric Tree - Python
Air’s Big Data
2020. 9. 4. 05:41
LeetCode 101. Symmetric Tree - Python
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Solution : Recursive
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root: #루트가 없으면 True 반환
return True
return self.check(root.left, root.right) #루트의 좌우 값 비교
def check(self, left, right):
if left is None and right is None: #좌우 둘다 없으면 True
return True
if left is None or right is None: #좌우 중 하나 없으면 False
return False
if left.val != right.val: #좌우 값이 다르면 False
return False
a = self.check(left.left, right.right) #좌의 좌 값, 우의 우 값 비교
b = self.check(left.right, right.left) #좌의 우값, 우의 좌 값 비교
return a and b
Solution : Iterative
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
stack = collections.deque([(root.left, root.right)])
while stack:
l, r = stack.pop()
if l is None and r is None:
continue
if l is None or r is None:
return False
if l.val != r.val:
return False
stack.append((l.left, r.right))
stack.append((l.right, r.left))
return True
(참고 사이트)