Simple Java BFS with Explanation (No recursion)


  • 0
    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            // return emptyList() if no input 
            if (root == null) return Collections.emptyList();  
            
            List<Integer> ret = new ArrayList<>(); 
            LinkedList<TreeNode> queue = new LinkedList<>();  
            
            // initialize queue 
            queue.add(root);
            
            while(!queue.isEmpty()){ 
                int currLens = queue.size(); 
               
                // get the rightmost node value 
                ret.add(queue.get(currLens-1).val); 
                
                // loop through current nodes to add their child(ren)
                for (int i = 0; i < currLens; i++){
                    TreeNode curr = queue.pop(); 
                   // add left & right nodes if exist (for next iteration)
                    if (curr.left != null) queue.add(curr.left); 
                    if (curr.right != null) queue.add(curr.right); 
                }
            }
            
            return ret; 
        }
    }
    

Log in to reply
 

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