Поиск в двоичном дереве с помощью Windows Forms C#

#c# #binary-tree #windows-forms-designer

#c# #двоичное дерево #windows-forms-designer

Вопрос:

Как и выше, я разрабатываю приложение, которое создает и сортирует 10 целых чисел. Мне нужно иметь возможность вводить целое число в поле поиска, нажимать кнопку поиска, и оно должно подтвердить, есть ли целое число через messagebox. Ниже приведен мой код.

 using Microsoft.TeamFoundation.Common.Internal;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TreeProject
{
    public partial class frmTask2 : Form
    {
        Tree MyTree;
        public frmTask2()
        {
            InitializeComponent();
        }
       

        private void btnClose2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnDisplay2_Click(object sender, EventArgs e)
        {
            Random rnd = new Random();
            int num;
            lblUnsorted.Text = "";
            lblSorted.Text = "";
            num = rnd.Next(0, 100);
            lblUnsorted.Text = lblUnsorted.Text   num.ToString().PadLeft(3);
            MyTree = new Tree(num);

            for(int i = 1; i< 10; i  )
            {
                num = rnd.Next(0, 100);
                lblUnsorted.Text = lblUnsorted.Text   num.ToString().PadLeft(3);
                MyTree.AddRc(num);
            }
            string treestring = "";
            MyTree.Print(null, ref treestring);
            lblSorted.Text = treestring;
        }

       

        private void btnSearch_Click(object sender, EventArgs e)
        {
           //Required code here
        }

        private void lblUnsorted_Click(object sender, EventArgs e)
        {

        }
    }
    class Node
    {
        public int value;
        public Node left;
        public Node right;

        public Node (int initial)
        {
            value = initial;
            left = null;
            right = null;
        }
    }

    class Tree
    {
        Node top;

        public Tree()
        {
            top = null;
        }
        public Tree(int initial)
        {
            top = new Node(initial);
        }

        public void AddRc(int value)
        {
            //recurse add
            AddR(ref top, value);
        }

        private void AddR(ref Node N, int value)
        {
            // private recursive search for where to add the new node
            if (N == null)
            {
                Node NewNode = new Node(value);
                N = NewNode;
                return;
            }
            if (value < N.value)
            {
                AddR(ref N.left, value);
                return;
            }
            if (value >= N.value)
                {
                AddR(ref N.right, value);
                return;
            }
        }
        public Node search(Node root,
                   int key)
        {
            // Base Cases: root is null  
            // or key is present at root 
            if (root == null ||
                root.value == key)
                return root;

            // Key is greater than root's key 
            if (root.value < key)
                return search(root.right, key);

            // Key is smaller than root's key 
            return search(root.left, key);
        }

        public void Print(Node N, ref string s)
        {
            // write out the tree in sorted order to the string newstring using recursion
            if (N == null) { N = top; }
            if (N.left != null)
            {
                Print(N.left, ref s);
                s = s   N.value.ToString().PadLeft(3);
            }
            else
            {
                s = s   N.value.ToString().PadLeft(3);
            }
            if (N.right != null)
            {
                Print(N.right, ref s);
            }
        }
        public bool ifNodeExists(Node node, int key)
        {
            if (node == null)
                return false;

            if (node.value == key)
                return true;

            // then recur on left sutree /
            bool res1 = ifNodeExists(node.left, key);

            // node found, no need to look further
            if (res1) return true;

            // node is not found in left, 
            // so recur on right subtree /
            bool res2 = ifNodeExists(node.right, key);

            return res2;
        }

    }
}
 

Дерево работает, я отображаю несортированные и отсортированные значения дерева с помощью меток, но я застрял в реализации кнопки поиска. Любая помощь будет оценена.

Комментарии:

1. Кнопка Seahc не работает? или работает неправильно?

2. Итак, вам нужно 1) получить целое число из поля ввода, 2) вызвать метод search или ifNodeExists вашего дерева, 3) отобразить результат в виде MessageBox, с каким из трех шагов у вас возникли проблемы?

3. Привет, Клаус, спасибо за ответ, 1 и 2.