My Java Solution


  • -1
    V
      public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> returnList = new ArrayList<List<Integer>>();
        List<TreeNode> currentLevel = new ArrayList<TreeNode>();
        if (root == null) return returnList;
        currentLevel.add(root);
    
        while (!currentLevel.isEmpty()){
            List<Integer> currentLevelInts = new ArrayList<Integer>();
            List<TreeNode> nextLevel = new ArrayList<TreeNode>();
            for (TreeNode treeNode : currentLevel) {
                if (treeNode.left!=null) nextLevel.add(treeNode.left);
                if (treeNode.right!=null) nextLevel.add(treeNode.right);
                currentLevelInts.add(treeNode.val);
            }
            currentLevel = nextLevel;
            returnList.add(currentLevelInts);
        }
        return returnList;
    }

Log in to reply
 

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