I tried to solve a symmetric tree problem
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
But the following
[1,2,2,null,3,null,3]
is not:1 / \ 2 2 \ \ 3 3
Note: Bonus points if you could solve it both recursively and iteratively.
My solution with recursion
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
if not root: return True #None is symmetic
return self.isMirror(root.left, root.right)
def isMirror(self, l, r):
if not l and not r: return True #base case 1
if not l or not r: return False #base case 2
if l.val != r.val: return False #base case 3
#recur case
left = self.isMirror(l.left, r.right)
right = self.isMirror(l.right, r.left)
return left and right
I assumed it as a decent solution to this problem but get a low score
Runtime: 32 ms, faster than 24.42% of Python online submissions for Symmetric Tree. Memory Usage: 12.2 MB, less than 5.08% of Python online submissions for Symmetric Tree.
How could improve the my solution?
TreeNode
objects? \$\endgroup\$