Question

Formatted question description: https://leetcode.ca/all/199.html

 199	Binary Tree Right Side View

 Given a binary tree, imagine yourself standing on the right side of it,
 return the values of the nodes you can see ordered from top to bottom.

 Example:

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

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

 @tag-tree

Algorithm

Just save the rightmost node of each level.

Code

Java

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Binary_Tree_Right_Side_View {

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<Integer> rightSideView(TreeNode root) {

            List<Integer> result = new ArrayList<>();

            if (root == null) {
                return result;
            }

            Queue<TreeNode> q = new LinkedList<>();
            q.offer(root);

            int currentLevelCount = 1;
            int nextLevelCount = 0;

            while (!q.isEmpty()) {
                TreeNode current = q.poll();
                currentLevelCount--;

                if (current.left != null) {
                    q.offer(current.left);
                    nextLevelCount++;
                }
                if (current.right != null) {
                    q.offer(current.right);
                    nextLevelCount++;
                }

                if (currentLevelCount == 0) {
                    result.add(current.val);
                    currentLevelCount = nextLevelCount;
                    nextLevelCount = 0;
                }
            }

            return result;
        }
    }
}

All Problems

All Solutions