alpenglow

basic_tree_impl

Sep 18th, 2021 (edited)
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.20 KB | None | 0 0
  1. using System;
  2.  
  3. namespace ConsoleApp1
  4. {
  5.     class Node
  6.     {
  7.         public int val { get; set; }
  8.         public Node left;
  9.         public Node right;
  10.         public Node(int d)
  11.         {
  12.             this.val = d;
  13.             left = null;
  14.             right = null;
  15.         }
  16.         public static void Insert(ref Node root, int val)
  17.         {
  18.             if (root == null) { root = new Node(val); return; }
  19.             if (root.val == val) { return; }
  20.             else if (val < root.val) { Insert(ref root.left, val); }
  21.             else { Insert(ref root.right, val); }
  22.  
  23.         }
  24.         public static void Traverse(Node root)
  25.         {
  26.             if (root is null) { return; }
  27.             Traverse(root.left);
  28.             Console.Write($"{root.val} ");
  29.             Traverse(root.right);
  30.         }
  31.     }
  32.  
  33.     class Program
  34.     {
  35.         static void Main(string[] args)
  36.         {
  37.             Random random = new Random(Guid.NewGuid().GetHashCode());
  38.             Node root = null;
  39.             for (int i = 0; i < 15; i++)
  40.             {
  41.                 Node.Insert(ref root, random.Next(0, 55));
  42.             }
  43.             Node.Traverse(root);
  44.             Console.WriteLine();
  45.         }
  46.     }
  47. }
  48.  
Add Comment
Please, Sign In to add comment