Recursive Java solution


  • 0
    F

    Didn't want to use a queue when it is a tree so I did a recursive solution.

    public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> nodes = new LinkedList<List<Integer>>();
            putInList(root,nodes,0);
            return nodes;
        }
        
        private void putInList(TreeNode node, List<List<Integer>> list, int depth) {
            if (node == null) return;
            while (list.size() <= depth) {
                list.add(new LinkedList<Integer>());
            }
            list.get(depth).add(node.val);
            putInList(node.left,list,depth+1);
            putInList(node.right,list,depth+1);
        }
    }

Log in to reply
 

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