code:
层次遍历打印每层最后一个
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null) {
return list;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int cur_num = 1;
int next_cur_num = 0;
TreeNode tmp;
while(!queue.isEmpty()) {
tmp = queue.poll();
--cur_num;
if(tmp.left != null){
queue.add(tmp.left);
++ next_cur_num;
}
if(tmp.right != null) {
queue.add(tmp.right);
++ next_cur_num;
}
if(cur_num == 0){
list.add(tmp.val);
cur_num = next_cur_num;
next_cur_num = 0;
}
}
return list;
}
}