简体   繁体   中英

Why does my method print an empty list?

I'm trying to print a tree level by level in an ArrayList<ArrayList<Integer>> result . Each list in result is considered its own level.

Example:

         1                
        / \             
       2   3   
      / \ / \           
     4  5 6  7
==>  [1][2, 3][4, 5, 6, 7]

For some reason, I keep getting back an empty list. Here is my code:

public ArrayList<ArrayList<Integer>> printLevelByLevel(TreeNode root) {
  ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
  ArrayList<Integer> temp = new ArrayList<Integer>();
  if(root == null) return result;
  int levelCount = 0;
  Queue<TreeNode> q = new LinkedList<TreeNode>();
  q.add(root);
  while(true){
    levelCount = q.size();
    if(levelCount == 0) break;
    while(levelCount > 0){
        TreeNode curr = q.poll();
        temp.add(curr.data);
        if(curr.left != null){
            q.add(curr.left);
        }
        if(curr.right != null){
            q.add(curr.right);
        }
        levelCount--;
    } // end of inner while 
    result.add(temp);
    temp.clear();
  } // end of outter while loop 

 return result;
}

is my temp.clear() right? I try putting it in different places but still the same result. I know I can do this with two Queues but I want to be able to do it with one Queue .

Thanks.

Adding the same ArrayList instance (referenced by the temp variable) to your reuslt list multiple times is wrong, since your result will contain multiple empty lists (or, more accurately, multiple references to the same empty list) at the end.

You should create a new instance in each iteration instead of clearing the single instance references by temp :

while(true){
    levelCount = q.size();
    if(levelCount == 0) break;
    ArrayList<Integer> temp = new ArrayList<Integer>();
    while(levelCount > 0){
        TreeNode curr = q.poll();
        temp.add(curr.data);
        if(curr.left != null){
            q.add(curr.left);
        }
        if(curr.right != null){
            q.add(curr.right);
        }
        levelCount--;
    } // end of inner while 
    result.add(temp);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM