Skip to content

Commit e9aa163

Browse files
committed
Create 101. Symmetric Tree.py
1 parent 8cfb5d8 commit e9aa163

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

101. Symmetric Tree.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# -*- coding: utf-8 -*-
2+
# @Time : 2019/3/6 14:35
3+
# @Author : xulzee
4+
5+
# @File : 101. Symmetric Tree.py
6+
# @Software: PyCharm
7+
8+
# Definition for a binary tree node.
9+
class TreeNode:
10+
def __init__(self, x):
11+
self.val = x
12+
self.left = None
13+
self.right = None
14+
15+
16+
class Solution:
17+
def isSymmetricHelper(self, left: TreeNode, right: TreeNode) -> bool:
18+
if left is None and right is None:
19+
return True
20+
if (left is None and right != None) or (left != None and right == None) or (left.val != right.val):
21+
return False
22+
return self.isSymmetricHelper(left.left, right.right) and self.isSymmetricHelper(left.right, right.left)
23+
24+
def isSymmetric1(self, root: TreeNode) -> bool:
25+
if root == None:
26+
return True
27+
return self.isSymmetricHelper(root.left, root.right)
28+
29+
def isSymmetric(self, root: TreeNode) -> bool:
30+
q = []
31+
q.append(root)
32+
q.append(root)
33+
while len(q) != 0:
34+
left = q.pop(0)
35+
right = q.pop(0)
36+
if left is None and right is None:
37+
continue
38+
if (left is None and right is not None) or (left is not None and right is None) or (left.val != right.val):
39+
return False
40+
q.append(left.left)
41+
q.append(right.right)
42+
q.append(left.right)
43+
q.append(right.left)
44+
return True

0 commit comments

Comments
 (0)