2023-12-13 树的层次遍历和树的反转以及树的对称

2023-12-14 00:51:12

二叉树的层次遍历、翻转二叉树和对称二叉树

102. 二叉树的层序遍历

核心:BFS广度优先遍历,就是维护一对队列去遍历!队列先进先出,符合一层一层遍历的逻辑。

102二叉树的层序遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def levelOrder1(self, root: Optional[TreeNode]) -> List[List[int]]:
        # 使用BFS广度优先搜索
        if not root:
            return []
        result = []
        queue = [root]
        while queue:
            temp = []
            for i in range(len(queue)):
                node = queue.pop(0)
                temp.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            result.append(temp)
        return result

226. 翻转二叉树

思想:只要把每一个节点的左右孩子翻转一下,就可以达到整体翻转的效果

翻转二叉树

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        # 使用递归来做
        if not root:
            return root
        root.right, root.left = root.left, root.right
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

101. 对称二叉树

思想:利用层次遍历得到的数,然后对比一下!左右是否相等

101.对称二叉树

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric1(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return False
        result = []
        queue = [root]
        while queue:
            temp = []
            for _ in range(len(queue)):
                node = queue.pop(0)
                if node:
                    temp.append(node.val)
                    queue.append(node.left)
                    queue.append(node.right)
                else:
                    temp.append(None)
            if temp != temp[::-1]:
                return False
        return True

文章来源:https://blog.csdn.net/niuzai_/article/details/134982285
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。