题目:
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 <--- / 2 3 <--- 5 4 <---
You should return [1, 3, 4]
.
看到这道题,我首先猜测可能和树的某种遍历方式有关,因为思路就往如何利用遍历的方向上去了。
观察发现,其实从右侧观察,能看到的就是层序遍历的每层最后一个元素。所以没啥好说的~~
1 public List<Integer> rightSideView(TreeNode root) { 2 List<Integer> res = new ArrayList<Integer>(); 3 if (root == null) { 4 return res; 5 } 6 Queue<TreeNode> q = new LinkedList<TreeNode>(); 7 q.offer(root); 8 while (!q.isEmpty()) { 9 int size = q.size(); 10 for (int i = 0; i < size; i++) { 11 TreeNode cur = q.poll(); 12 if (i == size - 1) { 13 res.add(cur.val); 14 } 15 if (cur.left != null) { 16 q.offer(cur.left); 17 } 18 if (cur.right != null) { 19 q.offer(cur.right); 20 } 21 } 22 } 23 return res; 24 }