Accepted Java recursive solution


  • 0
    X
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<List<Integer>> rv = new LinkedList<>();
            if(root == null) return rv;
            helper(rv, root, 0);
            return rv;
        }
        
        private void helper(List<List<Integer>> rv, TreeNode curr, int level){
            //Add new list for new level to front
            if(rv.size() - 1 < level) rv.add(0, new LinkedList<Integer>());
            //This allows us to access the reverse order position
            rv.get(rv.size() - 1 - level).add(curr.val); 
            if(curr.left!=null) helper(rv, curr.left, level+1);
            if(curr.right!=null) helper(rv, curr.right, level+1);
        }
    

Log in to reply
 

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