Share my easy Java Splution


  • 0
    A

    It is similar to question No.107. The only difference is the position that we put the temp list into the result list. Here, we simply append it to the end of the list.

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

Log in to reply
 

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