解题思路:
相当于层序遍历,然后取每一层的最后一个节点。
class Solution {public List<Integer> rightSideView(TreeNode root) {if (root == null) return new ArrayList<Integer>();Queue<TreeNode> queue = new LinkedList<>();List<Integer> list = new ArrayList<>();queue.add(root);while (!queue.isEmpty()) {TreeNode node = null;for (int i = queue.size(); i > 0; i--) {node = queue.poll();if (node.left != null) queue.add(node.left);if (node.right != null) queue.add(node.right);}list.add(node.val);}return list;}
}