The algorithm can be solved using BFS algorithm, level by level can be implemented to track nodes in the queue first; same level nodes will be visited one by one using a while loop by tracking count of nodes.
Here are highlights:
- Learn the technique to apply BFS using Queue, and track level by level by tracking nodes in the queue;
- For each level, calculate sum of each node's value; data type of sum should be long not int, and then average value will be double, so it is better to declare as double type;
- I completed the solution using 13 minutes.
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<double> AverageOfLevels(TreeNode root)
{
var averages = new List<double>();
if (root == null)
return averages;
var queue = new Queue<TreeNode>();
queue.Enqueue(root);
// push into queue by level
while(queue.Count > 0)
{
var count = queue.Count;
double sum = 0;
for(int i = 0; i < count; i++)
{
var current = queue.Dequeue();
sum += current.val;
if (current.left != null)
queue.Enqueue(current.left);
if (current.right != null)
queue.Enqueue(current.right);
}
averages.Add(sum/count);
}
return averages;
}
}
No comments:
Post a Comment