LeetCode101. 对称二叉树 (递归) + (迭代)

LeetCode101. 对称二叉树 (递归) + (迭代)

  • 递归

class Solution:
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root:
            return self.dfs(root.left, root.right)
        if not root:
            return True

    def dfs(self, l: TreeNode, r: TreeNode):
        if l and r:
            return l.val == r.val and self.dfs(l.left, r.right) and self.dfs(l.right, r.left)
        else:
            return not l and not r
  • 迭代

class Solution:
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        q = [root.left, root.right]
        while q:
            t1 = q.pop()
            t2 = q.pop()
            if not t1 and not t2:
                continue
            elif t1 == None or t2 == None:
                return False
            elif t1.val != t2.val:
                return False
            q.append(t1.left)
            q.append(t2.right)
            q.append(t1.right)
            q.append(t2.left)
        return True

你可能感兴趣的:(Python,algorithm,LeetCode,BFS,Data,Structure)