leetcode101 python symmetric binary tree

Given a binary tree, check if it is mirror symmetric.

For example, binary trees  [1,2,2,3,4,4,3] are symmetric.

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

But the following  [1,2,2,null,3,null,3] is not mirror-symmetric:

    1
   / \
  2   2
   \   \
   3    3

python code

# 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):
        """
        :type root: TreeNode
        :rtype: bool
        """
        #The main idea is to refer to the leetcode100 question. Here, the left and right nodes of the root node are assumed to be two independent trees, so the problem solving is similar to 100. The difference: when recursive calling, because it is symmetrical, it is the left node of the left tree and the right node. tree right node, left tree right node and right tree left node
        #Define first, then call
        def isSameTree(p,q):
            if not p and not q:#Both binary trees are empty, recursive boundary, both are empty return true  
                return True  
            if p and q and p.val==q.val:  
                l=isSameTree(p.left,q.right)#, which is different from leetcode100. Recursion, re-run from the function entry each time, and perform recursive boundary judgment each time  
                r=isSameTree(p.right,q.left)  
                The return l and r#and operation only returns true when both l and r are true. return the value with only the last recursion boundary  
            else:  
                return False
        if not root:
            return True
        else:
            #p=root.left;q=root.right
            return isSameTree(root.left,root.right)
        




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325729347&siteId=291194637