[Java] Simple solution only using ArrayList


  • 6
    T
    public List<List<Integer>> levelOrder(TreeNode root) {
    	List<List<Integer>> result = new ArrayList<List<Integer>>();
    	if(root==null) return result;
    	ArrayList<TreeNode> level = new ArrayList<TreeNode>();
    	level.add(root);
    	
    	while(!level.isEmpty()){
    		ArrayList<Integer> values = new ArrayList<Integer>();
    		for(int i=0; i<level.size(); i++){
    			values.add(level.get(i).val);
    		}
    		result.add(values);
    		ArrayList<TreeNode> nextlevel = new ArrayList<TreeNode>();
    		for(int j=0 ;j<level.size(); j++){
    			if(level.get(j).left!=null) nextlevel.add(level.get(j).left);
    			if(level.get(j).right!=null) nextlevel.add(level.get(j).right);
    		}
    		level = nextlevel;
    	}
    	return result;
    }
    

    Geometrically very simple and straight forward. But might need more memory than usual.


  • 0
    T

    Why do you say "might need more memory"? The usual BFS uses a queue, usually a LinkedList in Java, which is already improved by using ArrayList. level and nextLevel usually would be in the queue anyway.

    Did you notice that your two for loops are the same? Is there a reason for doing it twice?


Log in to reply
 

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