This page looks best with JavaScript enabled

Leetcode 101 Symmetric Tree

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True

        def chk(L, R):
            # (N,1): F, (N,N): T
            # (1,2): F
            # (1,1): check
            if not L or not R:
                return not (bool(L)^bool(R))
            elif L.val!=R.val:
                return False
            else:
                return chk(L.left, R.right) and chk(L.right, R.left)

        return chk(root.left, root.right)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True

        qn = [root]
        while qn:
            tmp, v = [], []
            for n in qn:
                for _ in [n.left, n.right]:
                    if _:
                        tmp.append(_)
                        v.append(_.val)
                    else:
                        v.append(None)
            if v != v[::-1]:
                return False
            qn = tmp
        return True