101. Symmetric Tree Leetcode Python, symmetricleetcode
Given a binary tree, check whether it is a mirror of itself (ie, shortric around its center ).
For example, this binary tree is unsupported Ric:
1 / \ 2 2 / \ / \3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you cocould solve it both recursively and iteratively.
This question requires iterative and recursive solutions.
The recursive solution is concise.
1. The stop condition is left = None & right = None.
2. left. val = right. val compare left. left right. right & left. right. left
False if any condition is not true
# 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,left,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 return self.sym(root.left,root.right)
If the iterative solution requires two stacks to store the node
1. Store left and right to stack1 stack2 in sequence
2. When the stack is not empty, pop the node in sequence and take left and right.
For comparison
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,left,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 root.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 False #if n1.left==None or n2.right==None: # return False #if n1.right==None or n2.left==None: # return 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.right and n2.left: stack1.append(n1.right) stack2.append(n2.left) return True