2ms java solution (LinkedList as queue)


  • 0
    S
    public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> l = new LinkedList<List<Integer>>();
            if (root == null) { return l; }
            List<Integer> currL = new LinkedList<Integer>();
            l.add(currL);
            int depth = 1;
            TreeNode nextDepth = null;
            boolean newDepthNeeded = true;
            LinkedList<TreeNode> q = new LinkedList<TreeNode>();
            q.add(root);
            while (!q.isEmpty()) {
                TreeNode node = q.remove();
                if (node == nextDepth) {
                    depth++;
                    newDepthNeeded = true;
                    currL = new LinkedList<Integer>();
                    l.add(currL);
                }
                currL.add(node.val);
                
                if (node.left != null) {
                    q.add(node.left);
                    if (newDepthNeeded) {
                        nextDepth = node.left;
                        newDepthNeeded = false;
                    }
                }
                if (node.right != null) {
                    q.add(node.right);
                    if (newDepthNeeded) {
                        nextDepth = node.right;
                        newDepthNeeded = false;
                    }
                }
            }
            return l;
        }
    }

Log in to reply
 

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