0

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?

quamrana
  • 37,849
  • 12
  • 53
  • 71
Alice
  • 1,360
  • 2
  • 13
  • 28
  • `print( 3 or 4 )`, `print( 4 or 3 )`, `print( 3 and 4 )`, `print( 4 and 3 )` – furas Apr 10 '19 at 07:44
  • lol, interesting, thank you. @furas – Alice Apr 10 '19 at 07:46
  • (x and y) Returns x if x is False, y otherwise (x or y) Returns y if x is False, x otherwise – Ardein_ Apr 10 '19 at 07:48
  • 1
    you will see that `and` gives you second value, `or` gives first value. But try to use 0 (zero) which is treated similar to None or False or empty list and you see different results. – furas Apr 10 '19 at 07:48

0 Answers0