Skip to content

Instantly share code, notes, and snippets.

@unilecs
Last active July 5, 2024 02:31
Show Gist options
  • Save unilecs/74f5257fce6b8445d2f1cb1283e706ba to your computer and use it in GitHub Desktop.
Save unilecs/74f5257fce6b8445d2f1cb1283e706ba to your computer and use it in GitHub Desktop.
Задача. Рассыпать монеты
using System;
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val)
{
this.val = val;
}
}
public class Program
{
public static int Count;
public static int ShareCoins(TreeNode root) {
Count = 0;
Traverse(root);
return Count;
}
public static int Traverse(TreeNode node)
{
if (node == null)
return 0;
int left = Traverse(node.left);
int right = Traverse(node.right);
Count += Math.Abs(left) + Math.Abs(right);
return node.val + left + right - 1;
}
public static void Main()
{
Console.WriteLine("UniLecs");
// tests
var root1 = new TreeNode(3);
root1.left = new TreeNode(0);
root1.right = new TreeNode(0);
Console.WriteLine(ShareCoins(root1).ToString()); // 2
var root2 = new TreeNode(0);
root2.left = new TreeNode(3);
root2.right = new TreeNode(0);
Console.WriteLine(ShareCoins(root2).ToString()); // 3
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment