代码随想录算法训练营第15天|二叉树(二)

题目链接:102.二叉树层序遍历

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        queue=collections.deque([root])
        res=[]
        if not root:
            return []
        while queue:
            level=[]
            for i in range(len(queue)):
                cur=queue.popleft()
                level.append(cur.val)
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
            res.append(level)
        return res
        


        

题目链接:226.反转二叉树

思路:先交换左右子节点,再反转左右子树

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return root
        root.left,root.right=root.right,root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root


题目链接:101.对称二叉树

思路:若根节点为空,则一定是对称二叉树;比较左右子节点,若左右子节点都为空,则为对称二叉树,若存在其中一个节点为空,则不是对称二叉树;若左右子节点都存在,但是对应值不相等,也不是二叉树;若左右子节点都存在且对应值相等则判断左子树左节点和右子树右节点是否相等(外侧),左子树右节点与右子树左节点是否相等(内侧)

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        return self.compare(root.left,root.right)
    def compare(self,left,right):
        if left is None and right is None: return True
        elif left is None or right is None: return False
        elif left.val !=right.val: return False

        outside=self.compare(left.left,right.right)
        inside=self.compare(left.right,right.left)
        issame=outside and inside
        return issame
            

        
        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值