• [LeetCode in Python] 199 (M) binary tree right side view 二叉树的右视图


    题目

    https://leetcode-cn.com/problems/binary-tree-right-side-view

    给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

    示例:

    输入: [1,2,3,null,5,null,4]
    输出: [1, 3, 4]

    解释:

    1 <---
    /
    2 3 <---

    5 4 <---

    解题思路

    • BFS,按层遍历节点
    • 构造多层列表,将同层节点从左到右存于同一列表
    • 返回结果时,取每层列表的最后一个即可

    代码

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def rightSideView(self, root: TreeNode) -> List[int]:
            if not root: return []
    
            # - keep nodes in same level in level_list[level]
            level_list = []
    
            # - (node, level)
            q = [(root, 1)]
            while q:
                node,level = q.pop(0)
    
                # - expand level_list for next level
                while level > len(level_list):
                    level_list.append([])
    
                # - append nodes from left to right
                level_list[level-1].append(node.val)
    
                level += 1
                if node.left: q.append((node.left, level))
                if node.right: q.append((node.right, level))
            
            # - return only right most node of each level
            return [nodes[-1] for nodes in level_list]
    

    解题思路

    • 实际上没有必要存储整层的节点,只需要不停的更新最后一个节点就好

    代码

    class Solution:
        def rightSideView(self, root: TreeNode) -> List[int]:
            if not root: return []
    
            # - level_list[level] is the right most node val at level
            level_list = []
    
            # - (node, level)
            q = [(root, 1)]
            while q:
                node,level = q.pop(0)
    
                # - expand level_list for next level
                while level > len(level_list):
                    level_list.append(node.val)
    
                # - append nodes from left to right
                level_list[level-1] = node.val
    
                level += 1
                if node.left: q.append((node.left, level))
                if node.right: q.append((node.right, level))
            
            # - return only right most node of each level
            return level_list
    
  • 相关阅读:
    Nagios经check_http监视web申请书server多个tomcat维修
    一个测试SQL2005数据库连接JSP档
    android 36 线程通信
    android 35 ListView增删改差
    android 34 ListView进阶
    android 33 对话框控件
    android 32 Gallery:横着滚动的列表
    android 31 GridView
    android 30 下拉列表框:ArrayAdapter和Spinner.
    android 29 ArrarAdapter数组适配器
  • 原文地址:https://www.cnblogs.com/journeyonmyway/p/12749348.html
Copyright © 2020-2023  润新知