Java BFS 2ms

  • 1
     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;
            while (!q.isEmpty()) {
                int size = q.size();
                List<Integer> cur = new ArrayList<>();
                for (int i = 0; i < size; i++) {
                    TreeNode node = q.poll();
                    if (node.left != null) {
                    if (node.right != null) {
                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.