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 /** 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> result = new ArrayList<>(); 13 if (root == null) return result; 14 15 Queue<TreeNode> queue = new LinkedList<>(); 16 queue.offer(root); 17 18 while (!queue.isEmpty()) { 19 int size = queue.size(); 20 for (int i = 0; i < size; i++) { 21 TreeNode top = queue.poll(); 22 if (i == size - 1) { 23 result.add(top.val); 24 } 25 if (top.left != null) { 26 queue.add(top.left); 27 } 28 if (top.right != null) { 29 queue.add(top.right); 30 } 31 } 32 } 33 return result; 34 } 35 }