Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
min tree
//Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { public static int minChance = 1; public static int maxChance = 4; public static int crossOver = 3; public static int maxDepth = 10; public static void Main(string[] args) { var root = new Node(); root.Data = 1; BuildRandomTree(root, maxDepth); Console.WriteLine(MinLeafSum(root)+"\n\n"); root.PrettyPrint(); } public static Random r = new Random(); public static Random r2 = new Random(); public static void BuildRandomTree(Node root, int maxDepth) { if (maxDepth<0) return; //r = new Random(); int rand = r.Next(minChance, maxChance); if (rand < crossOver) { root.Left = new Node(r2.Next(-100, 100)); BuildRandomTree(root.Left, maxDepth-1); } //r = new Random(); if (rand > crossOver) rand = r.Next(minChance*2, maxChance*2); else rand = r.Next(minChance, maxChance); if(rand < crossOver) { root.Right = new Node(r2.Next(-100, 100)); BuildRandomTree(root.Right, maxDepth-1); } } public static int MinLeafSum(Node root) { if (root == null) { return 0; } Queue<Node> bfsQueue = new Queue<Node>(); bfsQueue.Enqueue(root); bfsQueue.Enqueue(null); bool isLeafFound = false; int minLeafSum = 0; while (bfsQueue.Count > 0 && !isLeafFound) { Node currNode = null; while(bfsQueue.Count > 0 && (currNode = bfsQueue.Dequeue()) != null) { if (currNode.Left == null && currNode.Right == null) { isLeafFound = true; minLeafSum += currNode.Data; Console.WriteLine("+ " + currNode.Data); } else { Console.WriteLine("Read " + currNode.Data); if(currNode.Left != null) bfsQueue.Enqueue(currNode.Left); if (currNode.Right != null) bfsQueue.Enqueue(currNode.Right); } } Console.WriteLine("End level"); // Mark level end. bfsQueue.Enqueue(null); } return minLeafSum; } } public class Node { public int Data; public Node Left; public Node Right; public Node(){} public Node(int a) { this.Data = a; } public void PrettyPrint() { PrettyPrint(this, string.Empty); } private static void PrettyPrint(Node n, string prefix) { if (n == null) { Console.WriteLine(prefix+"*******************"); return; } PrettyPrint(n.Left, prefix + p); Console.WriteLine(prefix + n.Data); PrettyPrint(n.Right, prefix + p); } private static string p = "\t|"; } }
run
|
edit
|
history
|
help
0
String combinations
actions and tasks
Full text search using Linqdb
Namespace basic
testing endpoint
timeleft
Delegates
Uri builder
Everyone can sen ,only me can edi
1