199. Binary Tree Right Side View -BFS

this part is the key point

if (i == 0) {
    res.add(cur.val);
}
// right first, so i == 0 is the right side's first node
if (cur.right != null) queue.offer(cur.right); 
if (cur.left != null) queue.offer(cur.left);

or

if (i == size - 1) {
    res.add(cur.val);
}
// or left, right, so size - 1 is the right side's first node
if (cur.left != null) queue.offer(cur.left);
if (cur.right != null) queue.offer(cur.right);

time: O(n)

space: O(D) to keep the queues, where D is a tree diameter. Let's use the last level to estimate the queue size. This level could contain up to N/2N/2 tree nodes in the case of complete binary tree.

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

DFS

use preorder (because not related to subtree)

how to know current depth? use a varible

```java
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        dfs(root, result, 1);
        return result;
    }
    private void dfs(TreeNode node, List<Integer> result, int depth) {
        if (node == null) {
            return;
        }

        if (depth > result.size()) {
            result.add(node.val);
        }
        dfs(node.right, result, depth + 1);
        dfs(node.left, result, depth + 1);
    }
}
```

Last updated