力扣hot100_二叉树(4)_python版本

一、199. 二叉树的右视图

  • 思路:
    直接复用层序遍历的代码,然后取每层的最后一个节点
  • 代码:
python 复制代码
class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        '''
        层序遍历取每层的第一个
        '''
        if not root: return []

        res = []
        queue = collections.deque()
        queue.append(root)
        while queue:
            tmp_res = []
            for _ in range(len(queue)):
                node = queue.popleft()
                tmp_res.append(node.val)
                if node.left:queue.append(node.left)
                if node.right:queue.append(node.right)
            res.append(tmp_res[-1])  # 只需要修改层序遍历的这里
        return res

二、114. 二叉树展开为链表

  • 思路:
    直接复用先序遍历,然后遍历结果,依次修改结果就行
  • 代码:
python 复制代码
class Solution:
    def flatten(self, root: Optional[TreeNode]) -> None:
        """
        Do not return anything, modify root in-place instead.
        可以先序遍历节点,将节点放到列表中,然后连接上各节点
        """
        def dfs(cur):
            if not cur:
                return
            res.append(cur)
            dfs(cur.left)
            dfs(cur.right)
        res = []
        dfs(root)
        for idx, n in enumerate(res):
            if idx == len(res)-1:  
                n.left = None
                n.right = None
            else:
                n.left = None
                n.right = res[idx+1]

三、105. 从前序与中序遍历序列构造二叉树

  • 思路:
    根据前中后序任意两个可以重建一颗二叉树,只靠前序和后序不是唯一的。
  • 代码:
python 复制代码
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if not preorder:  # 空节点
            return None
        left_size = inorder.index(preorder[0])  # 左子树的大小
        left = self.buildTree(preorder[1: 1 + left_size], inorder[:left_size])
        right = self.buildTree(preorder[1 + left_size:], inorder[1 + left_size:])
        return TreeNode(preorder[0], left, right)

四、889. 根据前序和后序遍历构造二叉树

  • 代码:
python 复制代码
class Solution:
    def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        if not preorder:  # 空节点
            return None
        if len(preorder) == 1:  # 叶子节点
            return TreeNode(preorder[0])
        left_size = postorder.index(preorder[1]) + 1  # 左子树的大小
        left = self.constructFromPrePost(preorder[1: 1 + left_size], postorder[:left_size])
        right = self.constructFromPrePost(preorder[1 + left_size:], postorder[left_size: -1])
        return TreeNode(preorder[0], left, right)
相关推荐
We་ct1 天前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·javascript·算法·leetcode·typescript
做怪小疯子1 天前
华为笔试0429
python·numpy
Warson_L1 天前
Dictionary
python
JAVA面经实录9171 天前
Java企业级工程化·终极完整版背诵手册(无遗漏、全覆盖、面试+落地通用)
java·开发语言·面试
淡海水1 天前
【AI模型】常见问题与解决方案
人工智能·深度学习·机器学习
王老师青少年编程1 天前
csp信奥赛C++高频考点专项训练之贪心算法 --【哈夫曼贪心】:合并果子
c++·算法·贪心·csp·信奥赛·哈夫曼贪心·合并果子
周杰伦fans1 天前
AutoCAD .NET 二次开发:深入理解 EntityJig 的工作原理与正确实现
开发语言·.net
叼烟扛炮1 天前
C++第二讲:类和对象(上)
数据结构·c++·算法·类和对象·struct·实例化
ZhengEnCi1 天前
02a-什么是矩阵
机器学习
天疆说1 天前
【哈密顿力学】深入解读航天器交会最优控制中的Hamilton函数
人工智能·算法·机器学习