using System; public class BinaryTree { public BinaryTree( T value, BinaryTree leftNode = null, BinaryTree rightNode = null) { this.Value = value; this.LeftNode = leftNode; this.RightNode = rightNode; } public T Value { get; private set; } public BinaryTree LeftNode { get; private set; } public BinaryTree RightNode { get; private set; } public void EachPreOrder(Action action) { action(this.Value); if (this.LeftNode != null) { this.LeftNode.EachPreOrder(action); } if (this.RightNode != null) { this.RightNode.EachPreOrder(action); } } public void EachInOrder(Action action) { if (this.LeftNode != null) { this.LeftNode.EachPreOrder(action); } action(this.Value); if (this.RightNode != null) { this.RightNode.EachPreOrder(action); } } public void EachPostOrder(Action action) { if (this.LeftNode != null) { this.LeftNode.EachPreOrder(action); } if (this.RightNode != null) { this.RightNode.EachPreOrder(action); } action(this.Value); } }
Tag: binary
How to convert decimal to binary number in C# using method
using System; using System.Text; class DecToBin { static void Main(string[] args) { long num = int.MaxValue * 2L; Console.WriteLine(DecimalToBinary(num)); // 11111111111111111111111111111110 } private static string DecimalToBinary(long num) { StringBuilder res = new StringBuilder(); while (num > 0) { res.Insert(0, num % 2); num /= 2; } return res.ToString(); } }
How to convert binary number to decimal in C# using method.
using System; class BinToDec { static void Main(string[] args) { string binary = "101"; Console.WriteLine(BinaryToDecimal(binary)); // will return 5 } private static long BinaryToDecimal(string binary) { long decimalNum = 0; for (int i = binary.Length - 1, pow = 0; i >= 0; i--, pow++) { decimalNum += int.Parse(binary[i].ToString()) * (long)Math.Pow(2, pow); } return decimalNum; } }