(剑指offer)28.对称二叉树

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

思路:
1.针对前序遍历定义一种对称的遍历算法,即:根-右孩子-左孩子
如果对称遍历和前序遍历相同则是对称子树。
2.特殊情况,节点值全部相同。(考虑保存叶子节点None指针即可)

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

class Solution:
    def isSymmetrical(self, pRoot):
        preList = self.preOrder(pRoot)
        mirrorList = self.mirrPreOrder(pRoot)
        if preList == mirrorList:
            return True
        return False

    def preOrder(self,pRoot):
        if pRoot == None:
            return [None]
        treeStack = []
        output = []
        pNode = pRoot
        while pNode or len(treeStack) > 0:
            while pNode:
                treeStack.append(pNode)
                output.append(pNode.val)
                pNode = pNode.left
                if not pNode:
                    output.append(None) # 只给output增加了None,treeStack没有增加None,仍然是刚才的节点
            if len(treeStack):
                pNode = treeStack.pop() #直接判断上一节点是否有右孩子,如果有加入output,如果没有output增加none
                pNode = pNode.right
                if not pNode:
                    output.append(None)
        return output


    def mirrPreOrder(self,pRoot):
        if pRoot == None:
            return [None]
        treeStack = []
        output = []
        pNode = pRoot
        while pNode or len(treeStack) > 0:
            while pNode:
                treeStack.append(pNode)
                output.append(pNode.val)
                pNode = pNode.right
                if not pNode:
                    output.append(None)
            if len(treeStack):
                pNode = treeStack.pop()
                pNode = pNode.left
                if not pNode:
                    output.append(None)
        return output
pNode1 = TreeNode(8)
pNode2 = TreeNode(6)
pNode3 = TreeNode(10)
pNode4 = TreeNode(5)
pNode5 = TreeNode(7)
pNode6 = TreeNode(9)
pNode7 = TreeNode(11)

pNode1.left = pNode2
pNode1.right = pNode3
pNode2.left = pNode4
pNode2.right = pNode5
pNode3.left = pNode6
pNode3.right = pNode7

S = Solution()
result = S.isSymmetrical(pNode1)
print(result)


上一篇:【剑指Offer】二叉搜索树的第k个结点


下一篇:剑指offer第58题:对称的二叉树