Likou-101 Symmetric Binary Tree

At first, I planned to use recursive traversal (root->left->right) and (root->right->left) to determine whether a binary tree is a symmetric binary tree. But there are always loopholes; later, I tried to combine the three traversals. To do the two, found that there are still loopholes.
The last thought is to add the empty node to the result list and solve it successfully.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        # 根左遍历,根右遍历,判断是否相同
        if root == None:
            return True
        po_left = []
        po_right = []
       
        def PostOrder_left(root):
            if root == None:
                po_left.append(None)
                return 
            po_left.append(root.val)
            PostOrder_left(root.left)
            PostOrder_left(root.right)

        def PostOrder_right(root):
            if root == None:
                po_right.append(None)
                return 
            po_right.append(root.val)
            PostOrder_right(root.right)
            PostOrder_right(root.left)
        
        PostOrder_left(root)
        PostOrder_right(root)
        # print(po_left)
        # print(po_right)
        return po_left == po_right

The second solution method refers to Likou's drawing solution algorithm 101 , and inputs two trees A and B at the same time, and judges whether the left and right subtrees of A and the right and left subtrees of B are symmetrical.

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        # 前序遍历两颗树
        def two_tree(t1, t2):
            # print('111')
            if t1 == None and t2 == None:
                return True
            elif not t1 or not t2:
                return False
            else:
                if t1.val == t2.val:
                    r1 = two_tree(t1.left, t2.right)
                    r2 = two_tree(t1.right, t2.left)
                    return r1 and r2
                else:
                    return False
        return two_tree(root, root)

Guess you like

Origin blog.csdn.net/tailonh/article/details/112344813