Search in node in binary tree

Write a program to search node in a Binary Tree

Solution

using System;

namespace SearchBinaryTree
{
    class Program
    {
        public static void Main()
        {
            var binaryTree = new BinaryTree<int>();
            binaryTree.Root = new Node<int>(10);
            binaryTree.Root.Left = new Node<int>(20);
            binaryTree.Root.Right = new Node<int>(30);
            binaryTree.Root.Left.Left = new Node<int>(40);
            binaryTree.Root.Left.Right = new Node<int>(50);
            binaryTree.Root.Right.Left = new Node<int>(60);
            binaryTree.Root.Right.Right = new Node<int>(70);
            binaryTree.Root.Right.Right.Left = new Node<int>(100);
            binaryTree.Root.Right.Right.Right = new Node<int>(80);
            binaryTree.Root.Right.Right.Right.Left = new Node<int>(90);
            binaryTree.SearchNode(binaryTree.Root, 100);
            Console.WriteLine(binaryTree.IsValuePresent ? "Value present in tree" : "Value not present in tree");
            Console.ReadLine();
        }
    }

    public class BinaryTree<T>
    {
        public Node<T> Root;

        public BinaryTree()
        {
            Root = null;
        }

        public bool IsValuePresent;

        public void SearchNode(Node<T> temp, T value)
        {
            if (Root == null)
            {
                Console.WriteLine("Tree is empty");
            }
            else
            {
                if (temp.Data.Equals(value))
                {
                    IsValuePresent = true;
                    return;
                }

                if (IsValuePresent == false && temp.Left != null) SearchNode(temp.Left, value);
                if (IsValuePresent == false && temp.Right != null) SearchNode(temp.Right, value);
            }
        }



    }


    public class Node<T>
    {
        public T Data;
        public Node<T> Left;
        public Node<T> Right;

        public Node(T data)
        {
            Data = data;
            Left = null;
            Right = null;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *