# 101. Symmetric Tree [easy] (Python)

## 题目链接

https://leetcode.com/problems/symmetric-tree/

## 题目原文

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
/ \
2   2
/ \ / \
3  4 4  3

But the following is not:

    1
/ \
2   2
\   \
3    3

## 思路方法

### 思路一

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
return self.mirror(root.left, root.right)

def mirror(self, left, right):
if not left or not right:
return left == right
if left.val != right.val:
return False
return self.mirror(left.left, right.right) and self.mirror(left.right, right.left)

### 思路二

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
stackl, stackr = [root.left], [root.right]
while len(stackl) > 0 and len(stackr) > 0:
left = stackl.pop()
right = stackr.pop()
if not left and not right:
continue
elif not left or not right:
return False
if left.val != right.val:
return False
stackl.append(left.left)
stackl.append(left.right)
stackr.append(right.right)
stackr.append(right.left)
return len(stackl) == 0 and len(stackr) == 0

### 思路三

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
queuel, queuer = [root.left], [root.right]
while len(queuel) > 0 and len(queuer) > 0:
left = queuel.pop()
right = queuer.pop()
if not left and not right:
continue
elif not left or not right:
return False
if left.val != right.val:
return False
queuel.insert(0, left.left)
queuel.insert(0, left.right)
queuer.insert(0, right.right)
queuer.insert(0, right.left)
return len(queuel) == 0 and len(queuer) == 0

PS: 新手刷LeetCode，新手写博客，写错了或者写的不清楚还请帮忙指出，谢谢！

07-01 2384
01-30 2257