Symmetric binary tree 101

Title: Given a binary tree, check if it is mirror-symmetrical. For example, a binary tree  [1,2,2,3,4,4,3]is symmetrical.

Source: https://leetcode-cn.com/problems/symmetric-tree/

Act one: their own code

Ideas: Stack realize, in fact, with the queue implementation is also OK, not much difference, the official code with the recursive

# Definition A for binary Tree Node. 
Class the TreeNode:
     DEF  the __init__ (Self, X): 
        self.val = X 
        self.left = None 
        self.right = None
 # executes a: 44 ms, 82.50% of all beat submission python3 user 
# memory consumption: 12.9 MB, defeated 99.02% of users in all python3 submission 
class Solution:
     DEF isSymmetric (Self, root: TreeNode) -> BOOL:
         DEF judge_symmetric (the p-, q):
             IF the p- iS None and q IS None:
                return 2
            elif p is None or q is None or (p.val != q.val):
                return False
            else:
                return True
        if root is None:
            return True
        stack = []
        stack.append((root.left, root.right))
        while stack:
            p,q = stack.pop()
            res = judge_symmetric(p,q)
            #Note that one can not return, as is true True == 1 
            IF == RES 2 :
                 Pass 
            elif RES: 
                stack.append ((p.left, q.right)) 
                stack.append ((p.right, q.left) ) 
            the else :
                 return False
         return True
 IF  the __name__ == ' __main__ ' : 
    duixiang = Solution () 
    the root = the TreeNode (. 1 ) 
    A = the TreeNode (2 ) 
    B = the TreeNode (2 ) 
    root.left = A 
    root.right= b
    a.left = TreeNode(4)
    a.right = TreeNode(3)
    b.left = TreeNode(4)
    b.right = TreeNode(3)
    a = duixiang.isSymmetric(root)
    print(a)
View Code

 

Guess you like

Origin www.cnblogs.com/xxswkl/p/11988888.html