2017-08-02 106 views
0

我正在嘗試查找二叉樹中每個級別的平均值。我在做BFS。我正在嘗試使用空節點來完成它。每當我找到一個虛擬節點時,這意味着我處於該級別的最後一個節點。我面臨的問題是,我無法使用此功能在樹中添加最後一級的平均值。有人能幫我嗎?二叉樹中每個級別的平均值

考慮範例[3,9,20,15,7] 我得到的輸出爲[3.00000,14.50000]。沒有得到最後一級是15和7 的平均這裏是我的代碼

/** 
* 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<Double> averageOfLevels(TreeNode root) { 
    List<Double> list = new ArrayList<Double>(); 
    double sum = 0.0; 
    Queue<TreeNode> q = new LinkedList<TreeNode>(); 
    TreeNode temp = new TreeNode(0); 
    q.offer(root); 
    q.offer(temp); 
    int count = 0; 
    while(!q.isEmpty()){ 
     root = q.poll(); 
     sum += root.val; 

     if(root != temp) 
     { 
      count++; 
      if(root.left != null){ 
       q.offer(root.left); 
      } 
      if(root.right != null){ 
       q.offer(root.right); 
      } 
     } 
     else 
     { 
      if(!q.isEmpty()){ 
      list.add(sum/count); 
      sum = 0; 
      count = 0; 
      q.add(temp);   
      } 
     } 

    } 
    return list; 
    } 
} 

回答

0

看看這段代碼,它執行每當你發現當前級別的結束標記:

if(!q.isEmpty()){ 
     list.add(sum/count); 
     sum = 0; 
     count = 0; 
     q.add(temp);   
    } 

if聲明似乎被設計爲檢查您是否已經結束樹中的最後一行,您可以通過注意到隊列中沒有更多的條目對應下一個級別來檢測。在這種情況下,您確實不希望將虛擬節點添加回隊列中(這會導致無限循環),但請注意,您並未計算剛剛完成的行中的平均值。

要解決這個問題,你要獨立補種隊列,這樣的計算的最後一行的平均值:

if(!q.isEmpty()){ 
     q.add(temp);   
    } 

    list.add(sum/count); 
    sum = 0; 
    count = 0; 

有一個新的邊界情況需要注意的,這是發生了什麼如果樹是完全空的。我會讓你弄清楚如何從這裏出發。祝你好運!

0

我會用樹的遞歸深度掃描。在每個節點上,我會將值推入具有一對的映射中。

我沒有測試該代碼,但它應該是沿線。

void scan(int level, TreeNode n, Map<Integer, List<Integer> m) { 
    List l = m.get(level); if (l==null) { 
    l = new ArrayList(); 
    m.put(level, l); 
    } 
    l.add(n.val); 
    int nextLevel = level + 1; 
    if (n.left != null) scan(nextLevel, n.left, m); 
    if (n.right != null) scan(nextLevel, n.right, m); 
} 

一旦掃描完成,我可以計算每個級別的平均值。

for (int lvl in m.keyset()) { 
    List l = m.get(lvl); 
    // MathUtils.avg() - it is obvious what it should be 
    double avg = MathUtils.avg(l); 
    // you code here 
}