题目

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:

  1. Input: [1,2,3,null,5,null,4]
  2. Output: [1, 3, 4]
  3. Explanation:
  4. 1 <---
  5. / \
  6. 2 3 <---
  7. \ \
  8. 5 4 <---

题意

站在一个二叉树的右边向左看,求从上到下能看到的所有元素。

思路

相当于取每一行的最右元素,层序遍历即可。


代码实现

Java

  1. class Solution {
  2. public List<Integer> rightSideView(TreeNode root) {
  3. List<Integer> ans = new ArrayList<>();
  4. Queue<TreeNode> q = new LinkedList<>();
  5. if (root != null) {
  6. q.offer(root);
  7. }
  8. while (!q.isEmpty()) {
  9. int size = q.size();
  10. TreeNode cur = null;
  11. while (size > 0) {
  12. cur = q.poll();
  13. if (cur.left != null) q.offer(cur.left);
  14. if (cur.right != null) q.offer(cur.right);
  15. size--;
  16. }
  17. ans.add(cur.val);
  18. }
  19. return ans;
  20. }
  21. }