簡體   English   中英

將元素添加到二進制搜索樹

[英]Adding elements to a binary search tree

能來嗎,請幫幫我。 我試圖將元素添加到二進制搜索樹中,但它不起作用。 似乎它僅添加第一個數字作為根元素,然后不再添加任何內容。 這是代碼。

主要方法:

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    int a = 1;
    int v, b, c;
    TNode1 j = new TNode1(0, null, null);
    BST1 s = new BST1();

    while (a == 1) {
        System.out.println("1.Add numeber\n2.Print\n3.Stop");
        v = kb.nextInt();

        switch (v) {
        case 1:
            System.out.println("Give a number");
            b = kb.nextInt();
            s.insert(b);
            break;

        case 2:
            s.Print();
            break;

        case 3:
            break;
        }
    }
}

在BST1類中:

public void insert(int x) {
    if (root == null) {
        root = new TNode1(x, null, null);
        lastFound = root;
    } else {
        lastFound = root.insert(x);
    }
}

在TNode類中:

protected int element;
protected TNode1 left;
protected TNode1 right;

public TNode1 insert(int x) {
    if (x < element) {
        if (left == null) {
            left = new TNode1(x, null, null);
            return left;
        } else
            return left.insert(x);
    } else if (x > element) {
        if (right == null) {
            right = new TNode1(x, null, null);
            return right;
        } else
            return right.insert(x);
    } else
        return this;
}

以下是打印方法:

在BST1類中:

public void Print() 
{
        root.Print();
        System.out.println(".");
}

在TNode1類中:

public void Print() 
{
        System.out.print("(");
        if (left != null) 
        {
            left.Print();
            System.out.print(this);
        }
        if (right != null) 
        {
            right.Print();
            System.out.print(")");
        }
}

一個問題是停止不會停止循環。 在停止的情況下,您需要將a = 1;設置a = 1;

最好調用s.insert ,它將創建root如果root不存在root.insert(x)否則調用root.insert(x)

TNodeinsert似乎正確。 您可能遇到的問題是print方法。 建議:

public void print(String path, TNode1 node) {
    System.out.println(path + ": " + node.getElement());
    if (node.hasLeft()) print(path + "L", node.getLeft());
    if (node.hasRight()) print(path + "R", node.getRight());
}

請注意,我在這里使用了很多輔助方法。 如果沒有它們,則需要實現它們。 您可以這樣調用print:

s.print("", s.getRoot());

編輯:

編輯完問題后,我們將獲得有關print方法的更多信息。 這是代碼:

public void Print() 
{
        System.out.print("(");
        if (left != null) 
        {
            left.Print();
            System.out.print(this);
        }
        if (right != null) 
        {
            right.Print();
            System.out.print(")");
        }
}

問題:

  • 代替System.out.print(this)您需要System.out.print(this.getElement())print int而不是this
  • 在右側,您沒有print該元素,請看一下我上面的print ,它會啟發您

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM