Java BFS 2ms


  • 1
    Z
     public List<List<Integer>> levelOrderBottom(TreeNode root) {
            // first intuitive idea is just the same as level order and still use ArrayList
            // then reverse it, but we will have extra O(n) time complexity
            // Thanks to the discussion, they suggested to add at head.
            // then we should implement result as LinkedList not ArrayList anymore, because 
            // insert at ArrayList's head is so expensive.
            List<List<Integer>> res = new LinkedList<>();
            Queue<TreeNode> q = new LinkedList<>();
            if (root == null) {
                return res;
            }
            q.offer(root);
            while (!q.isEmpty()) {
                int size = q.size();
                List<Integer> cur = new ArrayList<>();
                for (int i = 0; i < size; i++) {
                    TreeNode node = q.poll();
                    cur.add(node.val);
                    if (node.left != null) {
                        q.offer(node.left);
                    }
                    if (node.right != null) {
                        q.offer(node.right);
                    }
                }
                res.add(0, cur);
            }
            return res;
        }
    

Log in to reply
 

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