Right View of a Binary Tree

Algorithm Steps

  1. Given a binary tree, if the tree is empty, return an empty result.
  2. Initialize a queue and enqueue the root node.
  3. While the queue is not empty, determine the number of nodes at the current level (levelSize).
  4. For each node in the current level, dequeue a node.
  5. If the node is the last one in the level (i.e. for index i == levelSize - 1), record its value as part of the right view.
  6. Enqueue the left and then right child of the node (if they exist) for processing in the next level.
  7. Repeat until all levels are processed; the recorded values form the right view of the binary tree.

Right View of a Binary Tree - Iterative Code Examples Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def rightView(root):
    if not root:
        return []
    result = []
    queue = [root]
    while queue:
        levelSize = len(queue)
        for i in range(levelSize):
            node = queue.pop(0)
            if i == levelSize - 1:
                result.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
    return result

if __name__ == '__main__':
    # Construct binary tree:
    #         1
    #        / \
    #       2   3
    #        \    \
    #         5    4
    root = TreeNode(1, TreeNode(2, None, TreeNode(5)), TreeNode(3, None, TreeNode(4)))
    print(rightView(root))