Java solution: recursive, tweaking pre-order traversal


  • 0
    J
     public List<List<Integer>> levelOrder(TreeNode root) {
            
            List<List<Integer>> lists = new ArrayList<List<Integer>>();
            createLevelList(lists,root,0);
            return lists;
        }
        
        public static void createLevelList(List<List<Integer>> lists, TreeNode root, int level){
            
            if(root ==null){
                return;
            }
            List<Integer> list = null;
            if(lists.size() == level){
                list = new ArrayList<Integer>();
                lists.add(list);
            }else{
                list= lists.get(level);
            }
            list.add(root.val);
            createLevelList(lists,root.left,level+1);
            createLevelList(lists,root.right,level+1);
        }
    

Log in to reply
 

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