leetcode 199. Binary Tree Right Side View

 

不就是bfs,然后返回每层最后一个节点值吗

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        
        Queue<TreeNode> q = new LinkedList<>();
        if(root == null)
            return res;
        
        q.offer(root);
        while(!q.isEmpty()){
            int size = q.size();
            for(int i=0; i<size; i++){
                TreeNode cur = q.poll();
                if(i == size-1)
                    res.add(cur.val);
                if(cur.left != null)
                    q.offer(cur.left);
                if(cur.right != null)
                    q.offer(cur.right);
            }
        }
        return res;
    }
}

 

posted @ 2019-08-16 01:32  南山南北秋悲  阅读(118)  评论(0编辑  收藏  举报