# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def helper(left, right):
"""
compare if two nodes are the sames.
"""
if left == None and right == None:
return True
elif left == None or right == None: # one None and one val
return False
elif left.val != right.val:
return False
else:
return helper(left.left, right.right) and helper(left.right, right.left)
return helper(root, root)
Recursive approach is easier. How about iterative?
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.