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.

For example:

Given the following binary tree,

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

You should return [1, 3, 4].

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public List<Integer> rightSideView(TreeNode root) {
  12. List<Integer> res = new ArrayList<Integer>();
  13. if (root == null)
  14. return res;
  15. Queue<TreeNode> queue = new LinkedList<TreeNode>();
  16. queue.add(root);
  17. queue.add(null);
  18. List<Integer> list = new ArrayList<Integer>();
  19. while (!queue.isEmpty()) {
  20. TreeNode node = queue.poll();
  21. if (node != null) {
  22. list.add(node.val);
  23. if (node.left != null)
  24. queue.add(node.left);
  25. if (node.right != null)
  26. queue.add(node.right);
  27. } else {
  28. res.add(list.get(list.size() - 1));
  29. if (!queue.isEmpty())
  30. queue.add(null);
  31. }
  32. }
  33. return res;
  34. }
  35. }