Simple Java Solution


  • 0
    P
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            
            if (root == null) return Collections.emptyList();
            
            //output variable
            List<List<Integer>> level = new ArrayList<List<Integer>>();
            //frontiers treeNode
            List<TreeNode> frontier = new ArrayList<TreeNode>();
            frontier.add(root);
            //while we still have unvisited TreeNode
            while (!frontier.isEmpty()){
                List<TreeNode> next = new ArrayList<TreeNode>();
                List<Integer> currentLevelVals = new ArrayList<Integer>();
                for(TreeNode current : frontier){
                    //add values of each frontiers TreeNode
                    currentLevelVals.add(current.val);
                    
                    //ensure next level has non null TreeNode
                    if (current.left != null) {
                        next.add(current.left);
                    }
                    if (current.right != null){
                        next.add(current.right);
                    }
                }
                level.add(currentLevelVals);
                frontier = next;
            }
            
            return level;
        }
    }

Log in to reply
 

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