Given a binary tree, check whether it is a mirror of the itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / 2 2/\/3 4 4 3
But the following are not:
1 / 2 2 \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
This topic requires the solution of iterative and recursive.
The solution of recursive is more concise
1. Stop condition is Left==none & Right==none
2. Left.val==right.val comparison left.left Right.right & Left.right Right.left
Any condition that is not true is false.
# Definition for a binary tree node# class treenode:# def __init__ (self, x): # self.val = x# self.left = No ne# self.right = Noneclass solution: # @param root, a tree node # @return A Boolean def sym (Self,left,righ T): if Left==none and Right==none: return True if left and right and Left.val==right.val: return Self.sym (Left.left,right.right) and Self.sym (Left.right,right.left) else: return False def Issymmetric (self, root): if Root==none: return True return Self.sym (root.left,root.right)
If it's a iterative solution, you need two stacks to save node.
1. First put left and right in Stack1 Stack2
2. When the stack is not empty, the node pops out and then takes the left and right
To compare
The code is as follows
# Definition for a binary tree node# class treenode:# def __init__ (self, x): # self.val = x# Self.left = none# Self.right = Noneclass Solution: # @param root, a tree node # @return A Boolean def sym (Self,lef T,right): If Left==none and Right==none:return True if left and right and Left.val==right.val: Return Self.sym (Left.left,right.right) and Self.sym (left.right,right.left) Else:return False def issymmetric (self, root): If Root==none:return True if Root.left==none and Roo T.right==none:return True if Root.left==none or Root.right==none:return False stack1 =[] stack2=[] Stack1.append (root.left) stack2.append (root.right) while Len (Stack1)!=0 and Len ( Stack2)!=0:n1=stack1.pop () N2=stack2.pop () if N1.val!=n2.val:return fals E #if n1.left==none or N2.right==none: # return False #if n1.right==none or n2.left==none: # RET Urn False if N1.left==none and N2.right!=none or N1.left!=none and N2.right==none:return false If N1.right==none and N2.left!=none or N1.right!=none and N2.left==none:return False If N1.left and N2.right:stack1.append (n1.left) stack2.append (n2.right) if N1.ri Ght and N2.left:stack1.append (n1.right) stack2.append (n2.left) return True
101. Symmetric Tree Leetcode Python