Level order traversal with null as delimiter


  • 0
    S
    class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> result = new ArrayList();
            if (root == null) {
                return result;
            }
            
            Queue<TreeNode> queue = new LinkedList();
            queue.add(root);
            queue.add(null);
            // prev or last node in a level
            TreeNode prev = null;
            while(!queue.isEmpty()) {
                TreeNode node = queue.poll(); 
                // if node is not null continue BFS.
                if (node != null) {
                    if (node.left != null) {
                        queue.add(node.left);
                    }
                    if (node.right != null) {
                        queue.add(node.right);
                    }
                } else { // if node is null means thats the end of that level. Add the prev value into the result.
                    if(!queue.isEmpty()) {
                        queue.add(null);
                    }
                    result.add(prev.val);
                }
                prev = node;
                
            }
            
            return result;
        }
    }```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.