Recursive Java Solution faster than 90% of the solutions


  • 0
    B
    public class Solution {
        private List<List<Integer>> mainList = new ArrayList<>();
        public List<List<Integer>> levelOrder(TreeNode root) {
            traverse(root, 0);
            return mainList;
        }
        
        private void traverse(TreeNode node, int level){
            if(node!=null){
                if(level==mainList.size()) mainList.add(new ArrayList<Integer>());
                mainList.get(level).add(node.val);
                traverse(node.left, level+1);
                traverse(node.right,level+1);
            }
            
        }
    }

Log in to reply
 

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