I tried to solve a symmetric tree problem
Given a binary tree, check if it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree.
one / 2 2 / / 3 4 4 3
But the following
[1,2,2,null,3,null,3]It is not:
one / 2 2 3 3
Bonus points if I could solve them recursively and iteratively.
My solution with recursion.
# Definition for a binary tree node. # TreeNode class: # def __init __ (self, x): # self.val = x # self.left = None # self.right = None Class solution (object): def isSymmetric (self, root): if it is not root: return True #None is symmetric returns self.isMirror (root.left, root.right) def isMirror (self, l, r): yes no l and no r: returns True #base case 1 if it is not or not r: returns False #base case 2 if l.val! = r.val: return False #base case 3 # case of recovery left = self.isMirror (l.left, r.right) right = self.isMirror (l.right, r.left) go back to the left and right
I assumed it as a decent solution to this problem but I got a low score
Runtime: 32 ms, faster than 24.42% of Python's online shipments for Symmetric Tree.
Memory usage: 12.2 MB, less than 5.08% of Python's online presentations for Symmetric Tree.
How could I improve my solution?