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

主要内容

题目

层序遍历

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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        results = []
        if not root:
            return results
        from collections import deque
        que = deque([root])
        while que:
            s = len(que)
            res = []
            for _ in range(s):
                cur = que.popleft()
                res.append(cur.val)
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)
            results.append(res)
        return results     
# 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]]:
        results = []

        def helper(root,depth):
            # 终止条件
            if not root:
                return
            # 单层逻辑    
            if len(results) == depth:
                results.append([])
            results[depth].append(root.val)
            helper(root.left, depth + 1)
            helper(root.right, depth + 1)

        helper(root, 0)
        
        return results    

107. 二叉树的层序遍历 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]]:
        results = []
        if not root:
            return results
        from collections import deque
        que = deque([root])
        while que:
            l = len(que)
            res = []
            for _ in range(l):
                cur = que.popleft()
                res.append(cur.val)
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)
            results.append(res)
        return results[::-1]     

199.二叉树的右视图

链接

# 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]:
        results = []
        if not root:
            return results
        from collections import deque
        que = deque([root])
        while que:
            l = len(que)
            res = []
            for _ in range(l):
                cur = que.popleft()
                res.append(cur.val)
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)
            results.append(res)
        return [results[i][-1] for i in range(len(results))]   

637.二叉树的层平均值

链接

# 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]:
        results = []
        if not root:
            return results
        from collections import deque
        que = deque([root])
        while que:
            l = len(que)
            res = []
            for _ in range(l):
                cur = que.popleft()
                res.append(cur.val)
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)
            results.append(res)
        return [sum(results[i])/len(results[i]) for i in range(len(results))] 

429.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]]:
        results = []
        if not root:
            return results
        from collections import deque
        que = deque([root])
        while que:
            l = len(que)
            res = []
            for _ in range(l):
                cur = que.popleft()
                res.append(cur.val)
                if cur.children:
                    for child in cur.children:
                        que.append(child)
            results.append(res)
        return results 

515.在每个树行中找最大值

链接

        results = []
        if not root:
            return results
        from collections import deque
        que = deque([root])
        while que:
            l = len(que)
            res = []
            for _ in range(l):
                cur = que.popleft()
                res.append(cur.val)
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)
            results.append(res)
        return [max(results[i]) for i in range(len(results))] 

116.填充每个节点的下一个右侧节点指针

链接

"""
# 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
        from collections import deque
        que = deque([root])
        while que:
            l = len(que)
            for i in range(l):
                cur = que.popleft()
                if i < l - 1:
                    cur.next = que[0]
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)        
        return root    

117.填充每个节点的下一个右侧节点指针II

链接
同116

"""
# 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
        from collections import deque
        que = deque([root])
        while que:
            l = len(que)
            for i in range(l):
                cur = que.popleft()
                if i < l - 1:
                    cur.next = que[0]
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)        
        return root

104.二叉树的最大深度

链接

# 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:
        res = 0
        if not root:
            return res
        from collections import deque
        que = deque([root])
        while que:
            l = len(que)
            for _ in range(l):
                cur = que.popleft()
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)
            res += 1
        return res    

111.二叉树的最小深度

链接

# 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:
        res = 0
        if not root:
            return res
        from collections import deque
        que = deque([root])
        while que:
            l = len(que)
            res += 1
            for _ in range(l):
                cur = que.popleft()
                if cur.left or cur.right:
                    if cur.left:
                        que.append(cur.left)
                    if cur.right:
                        que.append(cur.right)
                else:
                    return res         
        return res   

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.left, root.right = root.right, root.left
    #     self.invertTree(root.left)
    #     self.invertTree(root.right)
    #     return root     

    # 迭代前序   
    # def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
    #     if not root:
    #         return root
    #     s = [root]
    #     while s:
    #         cur = s.pop()
    #         cur.left, cur.right = cur.right, cur.left
    #         if cur.right:
    #             s.append(cur.right)
    #         if cur.left:
    #             s.append(cur.left)
    #     return root      

    # 迭代层次
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return root
        from collections import deque
        que = deque([root])
        while que:
            l = len(que)
            for _ in range(l):
                cur = que.popleft()
                cur.left, cur.right = cur.right, cur.left
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return True
        return self.compare(root.left, root.right)    

    def compare(self, left, right):
        if not left and not right:
            return True
        elif left and not right:
            return False
        elif right and not left:
            return False
        elif right.val != left.val:
            return False

        # 单层逻辑
        outside = self.compare(left.left, right.right)
        inside = self.compare(left.right, right.left)

        return outside and inside
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值