Binary Tree Right Side View

public class Solution {
    public ArrayList<Integer> rightSideView(TreeNode root) {
        // 层遍历,利用queue http://bookshadow.com/weblog/2015/04/03/leetcode-binary-tree-right-side-view/
        ArrayList<Integer> res = new ArrayList<Integer>();
        if(root==null) return res;
        LinkedList<TreeNode> q = new LinkedList<TreeNode>();
        q.add(root);
        
        while(!q.isEmpty()){
            int len = q.size();
            for(int i=0; i< len; i++){
                TreeNode top = q.poll();
                if(i==0) res.add(top.val);
                if(top.right!=null) q.add(top.right);
                if(top.left!=null) q.add(top.left);
            }
        }
        return res;
    }
}

 

posted @ 2015-04-08 00:49  世界到处都是小星星  阅读(109)  评论(0编辑  收藏  举报