Loading

LeetCode problem#199

Binary Tree Right Side View

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

43 lines
1/**
2 * Definition for a binary tree node.
3 * public class TreeNode {
4 *     int val;
5 *     TreeNode left;
6 *     TreeNode right;
7 *     TreeNode() {}
8 *     TreeNode(int val) { this.val = val; }
9 *     TreeNode(int val, TreeNode left, TreeNode right) {
10 *         this.val = val;
11 *         this.left = left;
12 *         this.right = right;
13 *     }
14 * }
15 */
16class Solution {
17    public List<Integer> rightSideView(TreeNode root) {
18        Queue<TreeNode> queue = new LinkedList<>();
19        List<Integer> values = new LinkedList<>();
20        if (root == null) {
21            return values;
22        }
23
24        queue.offer(root);
25        while (!queue.isEmpty()) {
26            values.add(queue.peek().val);
27
28            int size = queue.size();
29            while (size > 0) {
30                TreeNode curr = queue.poll();
31                if (curr.right != null) {
32                    queue.offer(curr.right);
33                }
34                if (curr.left != null) {
35                    queue.offer(curr.left);
36                }
37                size--;
38            }
39        }
40
41        return values;
42    }
43}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.