iT邦幫忙

0

學校作業,瓶頸 || 寫出一個最有效率的二元樹搜尋方法

https://ithelp.ithome.com.tw/upload/images/20210419/20121991ZE3mwZ28IL.png

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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
class Node
{
public int data;
public Node leftNode = null;
public Node rightNode = null;

        public Node(int data)
        {
            this.data = data;
        }
    }
    Node root = null;
    public Form1()
    {
        InitializeComponent();
    }
    private Node searchNode(int nodeData)
    {
        return null;
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (root == null)
            root = insert(root, Convert.ToInt32(textBox1.Text));
        else
            insert(root, Convert.ToInt32(textBox1.Text));
        textBox1.Clear();
    }

    private Node insert(Node root, int key)
    {
        Node newNode = new Node(key);
        Node x = root;
        Node y = null;
        while (x != null)
        {
            y = x;
            if (key < x.data)
                x = x.leftNode;
            else
                x = x.rightNode;
        }
        if (y == null) //全空的樹
            y = newNode;
        else if (key < y.data)
            y.leftNode = newNode;
        else
            y.rightNode = newNode;
        return y;
    }

    private void inorder(Node node)
    {
        if (node != null)
        {
            inorder(node.leftNode);
            textBox2.AppendText(node.data.ToString() + " ");
            inorder(node.rightNode);
        }
    }

    private void preorder(Node node)
    {
        if (node != null)
        {
            textBox2.AppendText(node.data.ToString() + " ");
            preorder(node.leftNode);
            preorder(node.rightNode);
        }
    }

    private void postorder(Node node)
    {
        if (node != null)
        {
            postorder(node.leftNode);
            postorder(node.rightNode);
            textBox2.AppendText(node.data.ToString() + " ");
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        textBox2.AppendText("\r\n 中序: ");
        inorder(root);
    }

    private void button3_Click(object sender, EventArgs e)
    {
        textBox2.AppendText("\r\n 前序: ");
        preorder(root);
    }

    private void button4_Click(object sender, EventArgs e)
    {
        textBox2.AppendText("\r\n 後序: ");
        postorder(root);
    }
}

}

已知這些程序列式,請問各位版上的大神
還能有怎麼成列的方式能解救這個問題?

1 個回答

3
海綿寶寶
iT邦大神 1 級 ‧ 2021-04-19 10:51:43

Google 是寫過最多次作業的學生
而且從不抗拒也不喊累

小魚 iT邦大師 1 級 ‧ 2021-04-19 12:18:46 檢舉

真的沒聽它喊累,
只是常常說我中獎了.

我要發表回答

立即登入回答