牛客网-Python-对称的二叉树

题目描述

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

思路(参考

1.只要pRoot.left和pRoot.right是否对称即可
2.左右节点的值相等且对称子树(left.left, right.right );(left.rigth,right.left)也对称

代码

1.递归

#递归,两个树对称的条件是左子树的左子树和右子树的右子树相同;左子树的右子树和右子树的左子树相同
class Solution:
    def isSymmetrical(self, pRoot):
        # write code here
        if pRoot==None:
            return True
        left = pRoot.left
        right = pRoot.right
        return self.isSymmetricalHelper(left,right)
    def isSymmetricalHelper(self,left,right):
        if left==None and right == None:
            return True
        if left==None or right == None:
            return False
        if left.val==right.val and self.isSymmetricalHelper(left.left,right.right) and self.isSymmetricalHelper(left.right,right.left):
            return True
        return False

2.非递归

使用栈

# -*- 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 == None:
            return True
        stack = [(pRoot.left,pRoot.right)]
        while(stack):
            l,r = stack.pop()
            if l==None and r==None:
                continue
            if l==None or r==None:
                return False
            if l.val!=r.val:
                return False
            stack.append((l.left,r.right))
            stack.append((l.right,r.left))
        return True
posted @ 2020-02-12 15:21  ditingz  阅读(221)  评论(0编辑  收藏  举报