Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:1 / \ 2 2 / \ / \ 3 4 4 3
Example 1
Input : [1,2,2,null,3,null,3]
1
/ \
2 2
/ \ / \
3 3
Output
false
Example 2
Input : [1,null, null]
1
/ \
Output
true
Traverse through the nodes of tree using recursion - and find for cases below
i) Root Node is NULL
ii) Both Chil Nodes are NULL
iii) Left.Val == Right.Val
iv) Left.right == Right.left && Left.left == Right.right
class Solution(object):
def isSymmetric(self, root):
if root is None: return True
return self.solver(root.left, root.right)
def solver(self, left, right):
if left is None and right is None: return True
if left is None or right is None: return False
return left.val == right.val and self.solver(left.left, right.right) and self.solver(left.right, right.left)
Result
Runtime: 20 ms
Memory Usage: 12.9 MB
Runtime Beats 87.48% of Python Submission