Thursday 23 September 2021

Binary Search Tree

 



Simple & easy way to create binary search tree in C# or .net Core



using System; 

namespace BinarySearchTree

{

    public class Program

    {

        static void Main()

        {

            Node root = null;

            BinaryTree binaryTree = new BinaryTree();

 

            root = binaryTree.Insert(root, 5);

            root = binaryTree.Insert(root, 4);

            root = binaryTree.Insert(root, 2);

            root = binaryTree.Insert(root, 3);

            root = binaryTree.Insert(root, 7);

            root = binaryTree.Insert(root, 6);

            root = binaryTree.Insert(root, 8);

 

            binaryTree.Traverse(root);

 

            Console.ReadLine();

        }

 

    }

 

    class Node

    {

        public int value;

        public Node left;

        public Node right;

    }

 

    class BinaryTree

    {

        internal Node Insert(Node root, int value)

        {

            if (root is null)

            {

                root = new Node

                {

                    value = value

                };

            }           

            else if (value < root.value)

            {

                root.left = Insert(root.left, value);

            }

            else

            {

                root.right = Insert(root.right, value);

            }

 

            return root;

        }

 

        public void Traverse(Node root)

        {

            if (root is null) return; 

            Traverse(root.left);

            Console.Write($"{root.value} ");

            Traverse(root.right);

        }

    }

}

 

 


No comments:

Post a Comment