101. Symmetric Tree
本题判断一个二叉树是否为对称树
题目链接:
# 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 sym(self, left, right): if not left and not right: return True if left and right and left.val == right.val: return self.sym(left.left, right.right) and self.sym(left.right, right.left) return False def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True return self.sym(root.left,root.right) '''非递归''' class Solution(object): def isSymmetric(self, root): if not root: return True if not root.left and not root.right: #左右子树均为空 return True if not root.left or not root.right: #左右子树一个为空一个不为空 return False stackl = [] stackr = [] stackl.append(root.left) stackr.append(root.right) while stackl and stackr: sl = stackl.pop() sr = stackr.pop() if sl.val != sr.val: return False if (not sl.left and sr.right) or (sl.left and not sr.right): #左子树的左子节点为空右子树的右子节点不为空, return False if (not sl.right and sr.left) or (sl.right and not sr.left): #左子树的右子节点为空且右子树的左子节点不为空, return False if sl.left and sr.right: #左子树的左子节点和右子树的右子节点比较 stackl.append(sl.left) stackr.append(sr.right) if sl.right and sr.left: #左子树的子节点和右子树的右子节点比较 stackl.append(sl.right) stackr.append(sr.left) return True