剑指offer-28.对称的二叉树

题目来源:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof/

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

解法一:递归

逐个比对左右子树中对应节点的值是否相同即可。

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def recur(L, R):
            if not L and not R:
                return True
            if not L or not R or L.val != R.val:
                return False
            return recur(L.left, R.right) and recur(L.right, R.left)

        if not root:
            return True
        return recur(root.left, root.right)

解法二:迭代

借助队列来实现,思路与递归相同。

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root or (not root.left and not root.right):
            return True
        queue = [root.left, root.right]
        while queue:
            l = queue.pop(0)
            r = queue.pop(0)
            if not l and not r:
                continue
            if not l or not r or l.val != r.val:
                return False

            queue.append(l.left)        
            queue.append(r.right)

            queue.append(l.right)
            queue.append(r.left)
        return True

 参考:

https://leetcode-cn.com/problems/symmetric-tree/solution/dong-hua-yan-shi-101-dui-cheng-er-cha-shu-by-user7/

你可能感兴趣的:(剑指offer-28.对称的二叉树)