Java simple queue implementation


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

Log in to reply
 

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