Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
1 / \ 2 2 / \ / \ 3 4 4 3But the following is not:
1 / \ 2 2 \ \ 3 3
方法1:递归方法
def isSymmetric(self, root):
if not root: return True
return self.helper(root.left, root.right)
def helper(self, left, right):
# first make sure left and right is not none
if left and right:
if left.val == right.val:
return self.helper(left.left, right.right) and self.helper(left.right, right.left)
else:
return False
else:
# otherwise,return left == right
return left == right
Method 2: Iterative method, using a stack data structure to store data. First, add the left and right nodes of root (indicated by a list) to the stack. If the stack is not empty, pop up the left and right nodes. If the left and right nodes are not empty, judge Whether the values of the left and right nodes are equal, if they are equal, the left child of the left node, the right child of the right node, the right child of the left node, the left child of the right node, and so on are pushed into the stack. If the left and right nodes are available, judge whether the two nodes are equal, and enter the next cycle if they are equal.
def isSymmetric(self, root):
if not root: return True
stack = [[root.left, root.right]]
while stack:
node1, node2 = stack.pop()
if node1 and node2: # make sure not None
if node1.val != node2.val:
return False
else:
stack.append([node1.left, node2.right])
stack.append([node1.right, node2.left])
else:
if node1 == node2:
continue
else:
return False
return True