leetcood学习笔记-101-对称二叉树

题目描述:

leetcood学习笔记-101-对称二叉树

方法一:递归:

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.isMirror(root,root)
    def isMirror(self,t1,t2):
        if not t1 and not t2:
            return True
        elif not t1 or not t2:
            return False
        return t1.val == t2.val and self.isMirror(t1.right,t2.left) and self.isMirror(t1.left,t2.right)

方法二:迭代:

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        qlist = []
        qlist.append(root)
        qlist.append(root)
        while len(qlist)!=0:
            t1 = qlist.pop()
            t2 = qlist.pop()
            if(t1==None and t2==None):
                continue
            if(t1==None or t2==None):
                return False
            if(t1.val!=t2.val):
                return False
            qlist.append(t1.left)
            qlist.append(t2.right)
            qlist.append(t1.right)
            qlist.append(t2.left)
        return True