题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
解题思路
递归地交换位置来判断当前结点的左右子结点是否对称。
代码
Python(2.7.3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetrical(self, pRoot):
# write code here
if pRoot is None:
return True
return self.isSame(pRoot.left, pRoot.right)
def isSame(self, root1, root2):
if root1 is None and root2 is None:
return True
if root1 is not None and root2 is not None and root1.val == root2.val:
# 交换位置判断结点是否相等
return self.isSame(root1.left, root2.right) and self.isSame(root1.right, root2.left)
return False运行时间:32ms
占用内存:5944k