Cerner Interview Question -- Implement Binary Search Tree

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Memory_understanding
{
    class Node
    {
        private char val;
        public char Val { get; set; }
        public Node leftChild;
        public Node rightChild;

        public Node(char value)
        {
            this.Val= value;
            this.leftChild = null;
            this.rightChild = null;

        }
     }

    class BST_Operations
    {

        Node root;

        public BST_Operations()
        {
            root = null;
        }

        private void construct(char val,ref Node node)
        {
            if (node==null)
            {
                Node temp= new Node(val);
                node=temp;
                return;
               

            }
            if ((int)node.Val >= (int)val)
            {
                construct(val,ref node.leftChild);
                return;
            }

            if ((int)node.Val < (int)val)
            {
                construct(val, ref node.rightChild);
                return;

            }

        }

        public void add_node(char val)
        {
            construct(val,ref root);
        }

        public void PreOrder()
        {
        }

        public void Inorder(Node n , ref string str)
        {
            if (n == null)
            {
                n = root;
                //Console.WriteLine(n.Val);
            }
            if (n.leftChild != null)
            {
                Inorder(n.leftChild, ref str);
                str = str + n.Val.ToString().PadLeft(3);
                //Console.WriteLine(n.Val);
            }

            else
            {
                str = str + n.Val.ToString().PadLeft(3);
                //Console.WriteLine(n.Val);
            }

            if (n.rightChild != null)
            {
                Inorder(n.rightChild, ref str);
                //Console.WriteLine(n.Val);

            }
        }

        public void PostOrder()
        {
        }

    }

    class BST
    {
        public static void Main_()
        {
            BST_Operations n = new BST_Operations();
            n.add_node('C');
            n.add_node('E');
            n.add_node('R');
            n.add_node('N');
            n.add_node('E');
            n.add_node('R');

            string str = "";
            n.Inorder(null, ref str);
            Console.WriteLine(str);
            Console.ReadLine();

        }
    }


}

Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6