I am working on tree problem Symmetric Tree - LeetCode
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.
Read the following solution
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def isSym(l,r):
if l==None and r==None:
return True
elif (l and r ) ==None:
return False
if l.val == r.val:
return isSym(l.left,r.right) and isSym(l.right,r.left)
else:
return False
if not root:
return True
if root:
return isSym(root.left,root.right)
I am aware that elif (l and r ) ==None:
is l == None or r == Nne
, but this expression is anti-intuitive
In [5]: (3 or 4) == 4
Out[5]: False
In [6]: (3 and 4) == 4
Out[6]: True
How to interpret it intuitively, is it a trick play on precedence?