leetcode101 python symmetric binary tree __python

Source: Internet
Author: User

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

For example, the binary tree [1,2,2,3,4,4,3] is 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 = No
        Ne class solution:def issymmetric (self, Root): "": Type Root:TreeNode:rtype:bool "" #思路主要参考leetcode100题, here will be the root node of the left and right node as two separate trees, so the problem with 100 is similar to, the difference: recursive call, because it is symmetric, so is the Zo Shu left node and the right-hand tree right node, left tree right node and right tree left node #先定义  
            , after calling Def Issametree (p,q): If not p and not Q: #两二叉树皆为空, recursive boundary, both null return True If P and Q and P.val==q.val:l=issametree (p.left,q.right) #, differs from leetcode100. Recursion, each time again from the entrance of the function, every time the recursive boundary Judgment R=issametree (P.right,q.left) return L and R#and operation, need L and R are both TR UE, before returning true.
        Only the last recursive boundary return value Else:return False if not Root:return True
         else: #p =root.left;q=root.right return Issametree (root.left,root.right)




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.