[LeetCode in Python] 199 (M) binary tree right side view

topic

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

Given a binary tree, imagine yourself standing on the right side of it, returning the node values ​​that can be seen from the right side, in order from top to bottom.

Example:

Input: [1,2,3, null, 5, null, 4]
Output: [1, 3, 4]

Explanation:

1 <---
/
2 3 <---
\
5 4 <---

Problem-solving ideas

  • BFS, traversing nodes by layer
  • Construct a multi-layer list and store nodes of the same layer in the same list from left to right
  • When returning the result, just take the last one of each layer list

Code

# 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]

Problem-solving ideas

  • In fact, there is no need to store the entire layer of nodes, just keep updating the last node.

Code

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

Guess you like

Origin www.cnblogs.com/journeyonmyway/p/12749348.html