簡體   English   中英

為什么我的方法打印一個空列表?

[英]Why does my method print an empty list?

我正在嘗試在ArrayList<ArrayList<Integer>> result逐級打印樹。 result每個列表均視為其自己的級別。

例:

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

出於某種原因,我不斷返回一個空列表。 這是我的代碼:

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;
}

我的temp.clear()對嗎? 我嘗試將其放在不同的位置,但結果仍然相同。 我知道我可以用兩個做這個Queues ,但是我希望能夠有一個做到這一點Queue

謝謝。

將相同的ArrayList實例(由temp變量引用)多次添加到reuslt列表中是錯誤的,因為最后result將包含多個空列表(或更准確地說,是對同一空列表的多個引用)。

您應該在每次迭代中創建一個新實例,而不是通過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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM