Two queue Java solution


  • 0
    S
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
          ArrayList<List<Integer>> order = new ArrayList<List<Integer>>();
          ArrayDeque<TreeNode> q = new ArrayDeque<TreeNode>();
          ArrayDeque<TreeNode> nq = new ArrayDeque<TreeNode>();
          List<Integer> row = new ArrayList<Integer>();
          TreeNode curr;
          if (root == null) return order;
          q.offer(root);
          while(!q.isEmpty()) {
            while(!q.isEmpty()) {
              curr = q.poll();
              if(curr.left!=null) {
                nq.offer(curr.left);
              }
              if(curr.right!=null) {
                nq.offer(curr.right);
              }
              row.add(curr.val);
            }
            order.add(row);
            q = new ArrayDeque(nq);
            nq.clear();
            row = new ArrayList<Integer>();
            
          } 
          return order;
        }
    }
    

Log in to reply
 

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