每日一题:判断对称二叉树 by python (19.9.17)

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

有两种方法,一种是递归的:

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

class Solution:
    def isSymmetrical(self, pRoot):
        if pRoot == None:
            return True
        return self.compare(pRoot.left, pRoot.right)
    
    def compare(self, pRoot1, pRoot2):
        if not pRoot1 and not pRoot2:
            return True
        if not pRoot1 or not pRoot2:
            return False
        if pRoot1.val == pRoot2.val:
            if self.compare(pRoot1.left, pRoot2.right) :
                if self.compare(pRoot1.right, pRoot2.left):
                    return True
        return False

非递归方法:采用层序遍历,查询每一层是不是满足对称的关系

# -*- coding:utf-8 -*-
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    def isSymmetrical(self, pRoot):
        if pRoot == None:
            return True
        s = []
        s.append(pRoot.left)
        s.append(pRoot.right)
        while(len(s)!=0):
            right = s.pop(-1)
            left = s.pop(-1)
            if not left  and not right:
                continue    
            if not left  or not right: 
                return False
            if left.val != right.val:
                return False
            s.append(left.left)
            s.append(right.right)
            s.append(left.right)
            s.append(right.left)
        return True

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章