-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path101.symmetric-tree.py
46 lines (40 loc) · 1.23 KB
/
101.symmetric-tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#
# @lc app=leetcode id=101 lang=python3
#
# [101] Symmetric Tree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
import queue
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
queue = deque([root])
while queue:
leaf = [n.val for n in queue]
if not leaf == leaf[::-1]:
return False
leaf = [(l.left, l.right) for n in queue]
queue = [l for n in leaf for l in leaf if l]
leaf = []
for n in leaf:
for l in n:
leaf += 1 if l else 0
if not leaf == leaf[::-1]:
return False
return True
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def isSem(L, R):
if not L and not R: return True
if L and R and L.val == R.val:
return isSem(L.left, R.right) and isSem(L.right, R.left)
return False
return isSem(root, root)
# @lc code=end