【Leetcode笔记】二叉树的层序遍历

Leetcode原题链接:
二叉树的层序遍历
二叉树的层序遍历 II
二叉树的右视图
二叉树的层平均值
N 叉树的层序遍历
在每个树行中找最大值
填充每个节点的下一个右侧节点指针
填充每个节点的下一个右侧节点指针 II
二叉树的最大深度
二叉树的最小深度

一、思路

  • 采用队列实现,具体方法有点难形容出来,可以对照着下面的第一题来举例理解走一遍[1,2,3,4,5,6,7]。
  • 下面的十道题都主要用了层序遍历的方法实现,偶尔需要根据题目进行一些小的改进。

二、代码

1、二叉树的层序遍历

# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        queue = [root]
        result = []
        while queue:
            tmp = []
            for i in range(len(queue)):
                cur = queue.pop(0)
                tmp.append(cur.val)
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
            result.append(tmp)
        return result

2、二叉树的层序遍历 II

# 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 levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        result = []
        queue = [root]
        while queue:
            tmp = []
            size = len(queue)
            for i in range(size):
                cur = queue.pop(0)
                tmp.append(cur.val)
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
            result.append(tmp)
        return result[::-1]

3、二叉树的右视图

a.思路1:先层序遍历,再取每一个小组的最后一个

# 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 rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        result = []
        queue = [root]
        while queue:
            tmp = []
            size = len(queue)
            for i in range(size):
                cur = queue.pop(0)
                tmp.append(cur.val)
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
            result.append(tmp)
        realreturn = []
        for res in result:
            realreturn.append(res[-1])
        return realreturn

b.思路2:判断是否为当前组最后一个即size-1,如果是再提取出来

# 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 rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        result = []
        queue = [root]
        while queue:
            size = len(queue)
            for i in range(size):
                cur = queue.pop(0)
                if i == size-1:
                    result.append(cur.val)
                if cur.left:
                        queue.append(cur.left)
                if cur.right:
                        queue.append(cur.right)
        return result

4、二叉树的平均值

# 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 averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
        result = []
        queue = [root]
        while queue:
            tmp = []
            for i in range(len(queue)):
                cur = queue.pop(0)
                tmp.append(cur.val)
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
            result.append(sum(tmp) / len(tmp))
        return result

5、N 叉树的层序遍历

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def levelOrder(self, root: 'Node') -> List[List[int]]:
        if not root:
            return []
        result = []
        queue = [root]
        while queue:
            tmp = []
            for i in range(len(queue)):
                cur = queue.pop(0)
                tmp.append(cur.val)
                for child in cur.children:
                    queue.append(child)
            result.append(tmp)
        return result

children是个列表,看完解析才恍然大悟

6、在每个树行中找最大值

a.自写版

# 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 largestValues(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []        
        result = []
        queue = [root]
        while queue:
            num_max = []
            for i in range(len(queue)):
                node = queue.pop(0)
                if not num_max:
                    num_max.append(node.val)
                else:
                    num_max[0] = self.retBig(node.val, num_max[0])
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            result.append(num_max[0])
        return result

    def retBig(self, a, b):
        if a > b:
            return a
        else:
            return b
  • 自己写的代码其实有个奇怪的地方没解决,就是num_max初始化应该设为多少,解决方法取了个巧,不初始化,存在列表的第一个位置。。
  • 看完解析发现另一个小问题,比大小函数python自带的有,不用自己定义

b.优秀版

下面是解决以上两问题的代码:

  • 变量可以初始化为-inf
  • 比大小函数可以用max()
# 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 largestValues(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        result = []
        queue = collections.deque([root])
        while queue:
            level_size = len(queue)
            max_val = float('-inf')
            for _ in range(level_size):
                node = queue.popleft()
                max_val = max(max_val, node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            result.append(max_val)
        return result

7、填充每个节点的下一个右侧节点指针

"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""

class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if not root:
            return root
        queue = [root]
        while queue:
            size = len(queue)
            for i in range(size):
                node = queue.pop(0)
                if i < size-1:
                    node.next = queue[0]
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return root

8、填充每个节点的下一个右侧节点指针 II

"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""

class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if not root:
            return root
        queue = [root]
        while queue:
            size = len(queue)
            for i in range(size):
                node = queue.pop(0)
                if i < size-1:
                    node.next = queue[0]
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return root

9、二叉树的最大深度

# 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 maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        depth = 0
        queue = [root]
        while queue:
            size = len(queue)
            for i in range(size):
                node = queue.pop(0)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            depth += 1
        return depth

10、二叉树的最小深度

# 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 minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        queue = [root]
        min_depth = 1
        while queue:
            size = len(queue)
            for i in range(size):
                node = queue.pop(0)
                if node.left == None and node.right == None:
                    return min_depth
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            min_depth += 1
        return min_depth

三、总结

  • 没什么好总结的,记住这个神奇的层序遍历方法 =)

部分内容参考代码随想录

你可能感兴趣的:(leetcode,笔记,算法)