题目:
思路:由二叉树的层序遍历,可以一层一层的遍历每一层元素,当遍历到每一层最后一个加入结果数组即可。层序遍历可以看我上期文章。
java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList();
Queue<TreeNode> q = new LinkedList();
if(root == null) return res;
q.add(root);
while(!q.isEmpty()){
int l = q.size();
while(l > 0){
TreeNode cur = q.peek();
q.poll();
if(l == 1){
res.add(cur.val);
}
l--;
if(cur.left != null){
q.add(cur.left);
}
if(cur.right != null){
q.add(cur.right);
}
}
}
return res;
}
}