LeetCode Brush Question Record 3-No.101 Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

101. Symmetric Tree
Given a binary tree, check whether it is a mirror image of itself (ie: axisymmetric)
For example, this binary tree is symmetric:
    1
   / \
  2   2
 / \ / \
3  4 4  3
But the following is not:
    1
   / \
  2   2
   \   \
   3    3

Idea: This problem can be solved very well by recursion. At the beginning, the left subtree and the right subtree are recursively down. If the left subtree of the first tree and the right subtree of the second tree are recursively exactly the same, at the same time the first The right subtree of one tree and the left subtree of the second tree recursively are exactly the same, then the two trees are symmetrical. If the two subtrees of the root node are symmetrical, then the entire tree is symmetrical.

方法1:递归方法

def isSymmetric(self, root):
        if not root: return True
        return self.helper(root.left, root.right)

def helper(self, left, right):
# first make sure left and right is not none
        if left and right: 
            if left.val == right.val:
                return self.helper(left.left, right.right) and self.helper(left.right, right.left)
            else:
                return False
        else:
# otherwise,return left == right
            return left == right 

Method 2: Iterative method, using a stack data structure to store data. First, add the left and right nodes of root (indicated by a list) to the stack. If the stack is not empty, pop up the left and right nodes. If the left and right nodes are not empty, judge Whether the values ​​of the left and right nodes are equal, if they are equal, the left child of the left node, the right child of the right node, the right child of the left node, the left child of the right node, and so on are pushed into the stack. If the left and right nodes are available, judge whether the two nodes are equal, and enter the next cycle if they are equal.

   def isSymmetric(self, root):

        if not root: return True
    
        stack = [[root.left, root.right]]
        
        while stack:
            node1, node2 = stack.pop()
            if node1 and node2: # make sure not None
                if node1.val != node2.val:
                    return False
                else:
                    stack.append([node1.left, node2.right])
                    stack.append([node1.right, node2.left])
            else:
                if node1 == node2:
                    continue
                else:
                    return False
        
        return True





Guess you like

Origin blog.csdn.net/qq_22472047/article/details/80640875