[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
posted @ 2020-04-22 01:45  ET民工[源自火星]  阅读(269)  评论(0编辑  收藏  举报