[LeetCode] 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
题目的意识是判断二叉树是否是镜像的,网上很多方法都是用递归或者层层遍历的,我觉得我们可以根据先序 + 中序 + 后序来判断,最直观来讲,如果一棵树是镜像二叉树,那么他的先序遍历和后续遍历正好相反,并且它的中序遍历序列也是关于中点元素对称的,另外,如果一个二叉树是镜像树,那么它的接点一定为奇数(空树除外)。基于这样判断,代码如下:

class TreeNode:
	def __init__(self, x):
		self.val = x
		self.left = None
		self.right = None

class Solution:
	# @param root, a tree node
	# @param sum, an integer
	# @return a boolean
	
	def scanTree(self, root, pre, mid, aft):
		if None == root:
			return 0
			
		pre.append(root.val)
		self.scanTree(root.left, pre, mid, aft)
		mid.append(root.val)
		self.scanTree(root.right, pre, mid, aft)
		aft.append(root.val)
		
	def isSymmetric(self, root):
		if None == root:
			return True
		pre = []
		aft = []
		mid = []
		self.scanTree(root, pre, mid, aft)
		liLen = len(aft)
		if liLen % 2 == 0:
			return False
		for i in xrange(liLen):
			if pre[i] != aft[liLen - i - 1]:
				return False
		for i in xrange(liLen / 2):
			if mid[i] != mid[liLen -i - 1]:
				return False
		return True




版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(算法,递归,python,二叉树,遍历)