Simple solution use recursion but without level checking


  • 0
    W
    class Solution {
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            final List<List<Integer>> res = new ArrayList<>();
            
            if (root == null) {
                return res;
            }
            
            final Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            
            helper(res, queue);
            
            return res;
        }
        
        private void helper(List<List<Integer>> res, Queue<TreeNode> queue) {
            if (queue.isEmpty()) {
                return;
            }
            
            final List<Integer> list = new ArrayList<>();
            
            for (int i = 0, len = queue.size(); i < len; ++i) {
                final TreeNode node = queue.poll();
                
                list.add(node.val);
                checkAndOffer(queue, node.left);
                checkAndOffer(queue, node.right);
            }
            
            helper(res, queue);
            res.add(list);
        }
        
        private void checkAndOffer(Queue<TreeNode> queue, TreeNode node) {
            if (node != null) {
                queue.offer(node);
            }
        }
    }
    

Log in to reply
 

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