101. Symmetric Tree

来源:互联网 发布:ipc h10网络摄像机 编辑:程序博客网 时间:2024/05/17 01:42

本题判断一个二叉树是否为对称树

题目链接:

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 Trueif left and right and left.val == right.val:return self.sym(left.left, right.right) and self.sym(left.right, right.left)return Falsedef isSymmetric(self, root):""":type root: TreeNode:rtype: bool"""if not root:return Truereturn self.sym(root.left,root.right)'''非递归'''class Solution(object):def isSymmetric(self, root):if not root:return Trueif not root.left and not root.right: #左右子树均为空return Trueif not root.left or not root.right: #左右子树一个为空一个不为空return Falsestackl = []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 Falseif (not sl.left and sr.right) or (sl.left and not sr.right): #左子树的左子节点为空右子树的右子节点不为空,return Falseif (not sl.right and sr.left) or (sl.right and not sr.left): #左子树的右子节点为空且右子树的左子节点不为空,return Falseif 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


原创粉丝点击