|
1 |
| -#!/usr/bin/python |
2 |
| -# -*- coding: utf-8 -*- |
3 |
| - |
4 |
| -# Author: Yu Zhou |
5 |
| -# **************** |
6 |
| -# Descrption: |
7 |
| -# 101. Symmetric Tree |
8 |
| -# Given a binary tree, check whether it is a mirror of itself |
9 |
| -# (ie, symmetric around its center). |
10 |
| -# **************** |
11 |
| - |
12 |
| -# 思路: |
13 |
| -# 这道题只要知道一个规律,就是左边Child要等于右边Child,就很容易了 |
14 |
| -# 先解决Root的Edge,之后在对其他进行一个统一处理,我选择写一个Helper,也可以不写 |
15 |
| - |
16 |
| -# if not left or not right: return left == right的意思是: |
17 |
| - # if not left or not right: return False |
18 |
| - # if not left and not right: return True |
19 |
| - |
20 | 1 | class Solution(object):
|
| 2 | + # Queue |
21 | 3 | def isSymmetric(self, root):
|
| 4 | + if not root: |
| 5 | + return True |
| 6 | + queue = [(root.left, root.right)] |
| 7 | + while queue: |
| 8 | + left, right = queue.pop(0) |
| 9 | + |
| 10 | + if not left and not right: |
| 11 | + continue |
| 12 | + if not left or not right: |
| 13 | + return False |
| 14 | + if left.val != right.val: |
| 15 | + return False |
| 16 | + queue.append((left.left, right.right)) |
| 17 | + queue.append((left.right,right.left)) |
| 18 | + return True |
| 19 | + |
| 20 | + |
| 21 | + # Recursion |
| 22 | + def isSymmetric2(self, root): |
| 23 | + if not root: |
| 24 | + return True |
22 | 25 |
|
23 |
| - if not root: return True |
24 | 26 | def dfs(left, right):
|
25 |
| - if not left or not right: return left == right |
26 |
| - if left.val != right.val: return False |
27 |
| - return dfs(left.left, right.right) and dfs(left.right, right.left) |
| 27 | + if not left and not right: |
| 28 | + return True |
| 29 | + if not left or not right: |
| 30 | + return False |
| 31 | + if left.val != right.val: |
| 32 | + return False |
| 33 | + return dfs(left.left , right.right) and dfs(left.right, right.left) |
28 | 34 |
|
29 | 35 | return dfs(root.left, root.right)
|
0 commit comments