LeetCode 101. Symmetric Tree(Python)

题目描述:
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.

思路1:
递归的思路是如果一棵树为镜像树,那么它的左右子树也一定为镜像树,且根节点的右子树和左子树相同。

递归AC代码:

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

思路2:
对该树进行逆转,通过对前后二次树均进行前序和中序遍历(因为前序遍历加中序遍历能够唯一确定一棵树),看两个结果是否相同来判断是否为镜像树。

AC代码:

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        ans = []
        def inOrderTravel(root):
            if root.left:
                inOrderTravel(root.left)
            ans.append(root.val)
            if root.right:
                inOrderTravel(root.right)
        def preOrderTravel(root):
            ans.append(root.val)
            if root.left:
                preOrderTravel(root.left)
            if root.right:
                preOrderTravel(root.right)
        def invert(root):
            temp = root.left
            root.left = root.right
            root.right = temp
            if root.left:
                invert(root.left)
            if root.right:
                invert(root.right)
        inOrderTravel(root)
        preOrderTravel(root)
        invert(root)
        inOrderTravel(root)
        preOrderTravel(root)
        if ans[:len(ans) // 2] == ans[len(ans) // 2:]:
            return True
        else:
            return False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值