简体   繁体   中英

Binary Search Tree in C# Implementation

class Node
{
    public int data;
    public Node left, right;

    public Node(int data)
    {
        this.data = data;
        left = null;
        right = null;

    }
}

class BinaryTreeImp
{
    Node root;
    static int count = 0;

    public BinaryTreeImp()
    {
        root = null;

    }
    public Node addNode(int data)
    { 
        Node newNode = new Node(data);

        if (root == null)
        {
            root = newNode;

        }
        count++;
        return newNode;


    }

    public void insertNode(Node root,Node newNode )
    {
        Node temp;
        temp = root;

        if (newNode.data < temp.data)
            {
                if (temp.left == null)
                {
                    temp.left = newNode;

                }

                else
                {
                    temp = temp.left;
                    insertNode(temp,newNode);

                }
            }
            else if (newNode.data > temp.data)
            {
                if (temp.right == null)
                {
                    temp.right = newNode;

                }

                else 
                {
                    temp = temp.right;
                    insertNode(temp,newNode);
                }
            }
        }


    public void displayTree(Node root)
    {
        Node temp;
        temp = root;

        if (temp == null)
            return;
            displayTree(temp.left);
            System.Console.Write(temp.data + " ");
            displayTree(temp.right);


    }

    static void Main(string[] args)
    {
       BinaryTreeImp btObj = new BinaryTreeImp();
       Node iniRoot= btObj.addNode(5);


       btObj.insertNode(btObj.root,iniRoot);
       btObj.insertNode(btObj.root,btObj.addNode(6));
       btObj.insertNode(btObj.root,btObj.addNode(10));
       btObj.insertNode(btObj.root,btObj.addNode(2));
       btObj.insertNode(btObj.root,btObj.addNode(3));
       btObj.displayTree(btObj.root);

       System.Console.WriteLine("The sum of nodes are " + count);
       Console.ReadLine();

    }
}

This is the code for implementation.The code works fine but if in the displayTree function , i replace it with

public void displayTree(Node root)
{
    Node temp;
    temp = root;

    while(temp!=null)
    {
        displayTree(temp.left);
        System.Console.Write(temp.data + " ");
        displayTree(temp.right);
    }

}

an infinite loop is caused. I don't understand what is causing this.Also i would like to know if there is a better way of implementing a BST in C#.

I'm not sure why you need this loop, but answering your question:

while(temp!=null)
{
    displayTree(temp.left);
    System.Console.Write(temp.data + " ");
    displayTree(temp.right);
}

this code checks if temp is not null , but it will never become null, cause inside the loop you act only on the leafs of the temp. That's why you have an infinit loop.

You don't need a while loop nor a temp variable, let recursion do the work for you:

public void displayTree(Node root)
{
    if(root == null) return;

    displayTree(root.left);
    System.Console.Write(root.data + " ");
    displayTree(root.right);
}

temp is set to root at the beginning, and after that its value never changes

what about rewriting your function as

public void displayTree(Node root)
{
     if (root == null)
       return;
     displayTree(root.left);
     Console.Write(...);
     displayTree(root.right);
}

try this

     public void displayTree(Node root) 
    {
        Node temp;
        temp = root;

        if (temp != null)
        {
            displayTree(temp.left);
            Console.WriteLine(temp.data + " ");
            displayTree(temp.right);

        }
    }

I was just thinking that you as well also could use recursion for the add function. It could look something like this

      private void Add(BinaryTree node, ref BinaryTree rootNode)
    {
        if (rootNode == null)
        {
            rootNode = node;
        }
        if (node.value > rootNode.value)
        {
            Add(node, ref rootNode.right);
        }
        if (node.value < rootNode.value)
        {

         Add(node, ref rootNode.left);
        }  
    }

See https://msdn.microsoft.com/en-us/library/ms379572%28v=vs.80%29.aspx . See the example code in the section "Traversing the Nodes of a BST"

Also... don't forget to check out SortedDictionary, etc. They may have the BST that you need all ready to go! https://msdn.microsoft.com/en-us/library/f7fta44c.aspx

Complete Binary Search Tree ... With Code to check whether Tree is balanced or not

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace BinarySearchTree
{

    public class Node
    {
        public Node(int iData)
        {
            data = iData;
            leftNode = null;
            rightNode= null;
        }
        public int data{get; set;}
        public Node leftNode{get; set;}
        public Node rightNode{get; set;}
    };
    public class Program
    {
        public static Node root = null;
        public static void Main(string[] args)
        {
            //Your code goes here
            Console.WriteLine("Hello, world!");
            root = new Node(20);
            InsertNode(root, new Node(10));
            InsertNode(root, new Node(15));
            InsertNode(root, new Node(13));
            InsertNode(root, new Node(11));
            InsertNode(root, new Node(12));
            InsertNode(root, new Node(25));
            InsertNode(root, new Node(22));
            InsertNode(root, new Node(23));
            InsertNode(root, new Node(27));
            InsertNode(root, new Node(26));


           if(CheckIfTreeIsBalanced(root))
           {
                Console.WriteLine("Tree is Balanced!");
           }
           else
           {
               Console.WriteLine("Tree is Not Balanced!");
           }
            PrintTree(root);
        }


        public static void PrintTree(Node root)
        {
           if(root == null) return;        
           Node temp = root;

           PrintTree(temp.leftNode);
           System.Console.Write(temp.data + " "); 
           PrintTree(temp.rightNode);

        }

        public static bool CheckIfTreeIsBalanced(Node root)
        {
            if(root != null)
            {
                if(root.leftNode != null && root.rightNode!= null)
                {
                    if(root.leftNode.data < root.data && root.rightNode.data > root.data)
                    {
                        return CheckIfTreeIsBalanced(root.leftNode)&&CheckIfTreeIsBalanced(root.rightNode);
                    }
                    else
                    {
                        return false;
                    }
                } 
                else if(root.leftNode != null)
                {
                    if(root.leftNode.data < root.data)
                    {
                        return CheckIfTreeIsBalanced(root.leftNode);
                    }
                    else
                    {
                        return false;
                    }
                }
                else if(root.rightNode != null)
                {
                    if(root.rightNode.data > root.data)
                    {
                        return CheckIfTreeIsBalanced(root.rightNode);
                    }
                    else
                    {
                        return false;
                    }
                }
            }
             return true;
        }

        public static void InsertNode(Node root, Node newNode )
        {
        Node temp;
        temp = root;

        if (newNode.data < temp.data)
            {
                if (temp.leftNode == null)
                {
                    temp.leftNode = newNode;

                }

                else
                {
                    temp = temp.leftNode;
                    InsertNode(temp,newNode);

                }
            }
            else if (newNode.data > temp.data)
            {
                if (temp.rightNode == null)
                {
                    temp.rightNode = newNode;

                }

                else 
                {
                    temp = temp.rightNode;
                    InsertNode(temp,newNode);
                }
            }
        }

    }
}

Output :

Hello, world!
Tree is Balanced!
10 11 12 13 15 20 22 23 25 26 27 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM