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

分析

层次遍历。

代码

  1. // Binary Tree Right Side View
  2. // 时间复杂度O(n),空间复杂度O(n)
  3. public class Solution {
  4. public List<Integer> rightSideView(TreeNode root) {
  5. List<Integer> result = new ArrayList<>();
  6. Queue<TreeNode> current = new LinkedList<>();
  7. Queue<TreeNode> next = new LinkedList<>();
  8. if(root == null) {
  9. return result;
  10. } else {
  11. current.offer(root);
  12. }
  13. while (!current.isEmpty()) {
  14. ArrayList<Integer> level = new ArrayList<>(); // elments in one level
  15. while (!current.isEmpty()) {
  16. TreeNode node = current.poll();
  17. level.add(node.val);
  18. if (node.left != null) next.add(node.left);
  19. if (node.right != null) next.add(node.right);
  20. }
  21. result.add(level.get(level.size()-1));
  22. // swap
  23. Queue<TreeNode> tmp = current;
  24. current = next;
  25. next = tmp;
  26. }
  27. return result;
  28. }
  29. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/binary-tree/traversal/binary-tree-right-side-view.html