LeetCode/problems/average-of-levels-in-binary-tree.cs

73 lines
1.6 KiB
C#
Raw Normal View History

problems(cs): add „637. Average of Levels in Binary Tree“ Signed-off-by: Matej Focko <mfocko@redhat.com> diff --git a/problems/average-of-levels-in-binary-tree.cs b/problems/average-of-levels-in-binary-tree.cs new file mode 100644 index 0000000..f2ba5aa --- /dev/null +++ b/problems/average-of-levels-in-binary-tree.cs @@ -0,0 +1,72 @@ +public class TreeNode +{ + public int val; + public TreeNode? left; + public TreeNode? right; + public TreeNode(int val = 0, TreeNode? left = null, TreeNode? right = null) + { + this.val = val; + this.left = left; + this.right = right; + } +} + + +public class Solution +{ + private class Level + { + long sum; + int counter; + + public Level() + { + sum = 0; + counter = 0; + } + + public void Add(int x) + { + sum += x; + counter++; + } + + public double Average + { + get => sum / (double)counter; + } + } + + private List<Level> AverageOfLevels(List<Level> averages, TreeNode? node, int level) + { + if (node == null) + { + return averages; + } + + if (level == averages.Count) + { + averages.Add(new Level()); + } + averages[level].Add(node.val); + + AverageOfLevels(averages, node.left, level + 1); + AverageOfLevels(averages, node.right, level + 1); + + return averages; + } + + public IList<double> AverageOfLevels(TreeNode? root) + => AverageOfLevels(new List<Level>(), root, 0).Select(level => level.Average).ToList(); + + public static void Main() + { + var s = new Solution(); + + foreach (var a in s.AverageOfLevels(new TreeNode(3, new TreeNode(9), new TreeNode(20, new TreeNode(15), new TreeNode(7))))) + { + Console.Write($"{a} "); + } + Console.WriteLine(); + } +}
2022-09-02 21:11:03 +02:00
public class TreeNode
{
public int val;
public TreeNode? left;
public TreeNode? right;
public TreeNode(int val = 0, TreeNode? left = null, TreeNode? right = null)
{
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution
{
private class Level
{
long sum;
int counter;
public Level()
{
sum = 0;
counter = 0;
}
public void Add(int x)
{
sum += x;
counter++;
}
public double Average
{
get => sum / (double)counter;
}
}
private List<Level> AverageOfLevels(List<Level> averages, TreeNode? node, int level)
{
if (node == null)
{
return averages;
}
if (level == averages.Count)
{
averages.Add(new Level());
}
averages[level].Add(node.val);
AverageOfLevels(averages, node.left, level + 1);
AverageOfLevels(averages, node.right, level + 1);
return averages;
}
public IList<double> AverageOfLevels(TreeNode? root)
=> AverageOfLevels(new List<Level>(), root, 0).Select(level => level.Average).ToList();
public static void Main()
{
var s = new Solution();
foreach (var a in s.AverageOfLevels(new TreeNode(3, new TreeNode(9), new TreeNode(20, new TreeNode(15), new TreeNode(7)))))
{
Console.Write($"{a} ");
}
Console.WriteLine();
}
}