My 3ms java solution


  • 0
    W

    public static List<List<Integer>> levelOrder(TreeNode root) {

    	List<List<Integer>> result = new ArrayList<List<Integer>>();
    	if (root==null) return result;
    	
        ArrayList<TreeNode> treeNodes = new ArrayList<TreeNode>();
        ArrayList<Integer> nodeLevel = new ArrayList<Integer>();
        List<Integer> subresult= new ArrayList<Integer>();;
        
        
        treeNodes.add(root);
        nodeLevel.add(0);
        int cLevel=0;
        
        while (treeNodes.size()!=0){
        	//deal with the first element in the queue
        	TreeNode node = treeNodes.get(0);
        	int level=nodeLevel.get(0);
        	
        	treeNodes.remove(0);
        	nodeLevel.remove(0);
        	
        	if ((level!=0)&&(level!=cLevel)){
        		result.add(subresult);
        		subresult= new ArrayList<Integer>();
        		cLevel++;
        	} 
        	
        	subresult.add(node.val);
        	
        	if (node.left!=null){
        		treeNodes.add(node.left);
        		nodeLevel.add(level+1);
        	}
        	
        	if (node.right!=null){
        		treeNodes.add(node.right);
        		nodeLevel.add(level+1);
        	}
        	
        }
        if (subresult.size()!=0) result.add(subresult);
        return result;
    }

Log in to reply
 

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