(offer) 28. Symmetric binary tree

Title Description
Please implement a function to determine whether a binary tree is symmetrical. Note that if a binary tree has the same mirror image as the binary tree, it is defined as symmetric.

Train of thought:
1. Define a symmetrical traversal algorithm for preamble traversal, i.e. root-right child-left child.
If symmetric traversal is the same as preamble traversal, it is symmetric subtree.
2. In special cases, the node values are all the same. (Consider saving the None pointer of the leaf node)

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) # It only adds None to output. TreeStack doesn't add None. It's still the node just now.
            if len(treeStack):
                pNode = treeStack.pop() #Direct judgment of whether the previous node has a right child, if you add output, if not output increase 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)


Posted by Zssz on Fri, 04 Oct 2019 03:12:01 -0700