Python实现"对称二叉树"的两种方法

给定一棵二叉树,检测它是否中心对称

例如,二叉树[1,2,2,3,4,4,3]是对称的

    1
   / \
  2   2
 / \ / \
3  4 4  3

但是二叉树[1,2,2,null,3,null,3]不是对称的

   1
   / \
  2   2
   \   \
   3    3

注意:如果你能用递归和迭代解决这个题会很加分

1:递归,解决方式和"相同的数"(https://mp.csdn.net/postedit/82318316)的第二种解法类似

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root == None:
            return True
        return self.checkTwoTree(root.left,root.right)
    def checkTwoTree(self, leftTree, rightTree):
        if leftTree==None and rightTree==None:
            return True
        if leftTree!=None and rightTree==None:
            return False
        if leftTree==None and rightTree!=None:
            return False
        if leftTree.val != rightTree.val:
            return False
        left = self.checkTwoTree(leftTree.left,rightTree.right)
        right = self.checkTwoTree(leftTree.right,rightTree.left)
        return left and right

2:迭代(有关递归和迭代的区别可以参考:https://blog.csdn.net/idaaa/article/details/78155553https://blog.csdn.net/u011514810/article/details/52749183

def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        nodeList = [root.left,root.right]
        while nodeList:
            symmetricLeft = nodeList.pop(0)
            symmetricRight = nodeList.pop(0)
            if not symmetricLeft and not symmetricRight:
                continue
            if not symmetricLeft or not symmetricRight:
                return False
            if symmetricLeft.val != symmetricRight.val:
                return False
            nodeList.append(symmetricLeft.left)
            nodeList.append(symmetricRight.right)
            nodeList.append(symmetricLeft.right)
            nodeList.append(symmetricRight.left)
        return True

算法题来自:https://leetcode-cn.com/problems/symmetric-tree/description/

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值