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

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

102. 二叉树的层序遍历

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

# 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. 对称二叉树

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

# 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

你可能感兴趣的:(二叉树)