Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

BFS

Time Complexity
O(N)
Space Complexity
O(N)

思路

用传统的BFS,唯一要加的是(i == size - 1)的时候,注意是size - 1, 因为i 是从0 开始的,size - 1就是每层的最右了,这时把这个数字加进res就可以

代码

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

annielulu
5 声望5 粉丝