Created
August 13, 2018 00:15
-
-
Save jianminchen/819637ac12eaf6724ec0af3853237b2d to your computer and use it in GitHub Desktop.
Leetcode 637 average of levels in binary tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace Leetcode_637_Average_of_levels_in_binary_tree | |
{ | |
class Program | |
{ | |
public class TreeNode | |
{ | |
public int val; | |
public TreeNode left; | |
public TreeNode right; | |
public TreeNode(int x) { val = x; } | |
} | |
static void Main(string[] args) | |
{ | |
} | |
/// <summary> | |
/// use a queue to traverse the tree by level, and then | |
/// add sum of all nodes in the same level, get average | |
/// | |
/// </summary> | |
/// <param name="root"></param> | |
/// <returns></returns> | |
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment