Share my AC Java solution with recursion


  • 0
    S

    This is my AC Java solution, using only recursion and avoiding the use of Collection.reverse. However it would be nice to take advantage of the method addFirst(E e) of LinkedList. So far I don't know how to implement it without getting compile error: https://oj.leetcode.com/discuss/21445/why-i-got-compile-error-with-my-java-solution
    This is the recursive solution:

    public class Solution {
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<List<Integer>> res = new LinkedList<List<Integer>>();
            if(root == null){
                return res;
            }
            List<TreeNode> level = new LinkedList<TreeNode>();
            level.add(root);
            doTraverse(res, level);
            return res;
            
        }
        public static void doTraverse(List<List<Integer>> res, List<TreeNode> current){
            if(current.isEmpty())
                return;
            List<TreeNode> next = new LinkedList<TreeNode>();
            List<Integer> temp = new LinkedList<Integer>();
            for(TreeNode node : current){
                temp.add(node.val);
                if(node.left != null)
                    next.add(node.left);
                if(node.right != null)
                    next.add(node.right);
            }
            doTraverse(res, next);
            res.add(temp);
        }
    }

Log in to reply
 

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