簡體   English   中英

我的二叉搜索樹不打印值,不知道是打印方式還是添加方式有問題

[英]My binary search tree won't print the values, and I don't know whether its the printing method or the adding method that's wrong

我正在嘗試創建二叉搜索樹,但代碼似乎不起作用。 我的 BinaryNode 的構造函數和變量

 private BinaryNode left;
 private BinaryNode right;
 public BinaryNode() {
     val = null;
     left = null;
     right = null;
 }
 public BinaryNode(String a, BinaryNode b, BinaryNode c) {
     val = a;
     left = b;
     right = c;
 }

這是我的 add 和 printPostOrder 方法。 BinaryNode x 是以 y 作為值的節點將成為子節點的根。

public BinaryNode add(BinaryNode x, String y) {
        if(x==null) {
            x = new BinaryNode(y,null,null);
            return x;
        }
        if(y.compareTo(x.getVal())<0) {
            BinaryNode temp = x.getLeft();
            temp = add(x.getLeft(),y);
            x.setLeft(x);
        }
            else if(y.compareTo(x.getVal())>0){
                BinaryNode temp = x.getRight();
                temp = add(x.getRight(),y);
                x.setLeft(x);
            }
        return x;
        }
 public void printPostOrder(BinaryNode x) {
        if(x!=null) {
            System.out.print(x.getVal()+" ");
            printPostOrder(x.getRight());
            printPostOrder(x.getLeft());
        }
    }

錯誤信息 -

    at sun.nio.cs.SingleByte.access$000(Unknown Source)
    at sun.nio.cs.SingleByte$Encoder.encodeArrayLoop(Unknown Source)
    at sun.nio.cs.SingleByte$Encoder.encodeLoop(Unknown Source)
    at java.nio.charset.CharsetEncoder.encode(Unknown Source)
    at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
    at sun.nio.cs.StreamEncoder.write(Unknown Source)
    at java.io.OutputStreamWriter.write(Unknown Source)
    at java.io.BufferedWriter.flushBuffer(Unknown Source)
    at java.io.PrintStream.write(Unknown Source)
    at java.io.PrintStream.print(Unknown Source)
    at BinarySearchTree.printPostOrder(BinarySearchTree.java:95)
    at BinarySearchTree.printPostOrder(BinarySearchTree.java:97)

最后一行重復多次。 幫助將不勝感激。

你的代碼有點亂,難以理解! 這是創建二叉搜索樹的簡單方法:

defination of bst class:
class BinaryNode {
    String val;
    BinaryNode left, right;
    public BinaryNode() {}
    public BinaryNode(String val) {
        this.val = val;
        this.left = this.right = null;
    }
    // setters - getters of all fields
 }



/* building bst */
private BinaryNode add(BinaryNode root, String val) {
    if(root == null) {
        root = new BinaryNode(val);
    }
    // if it is smaller than root's value, set in left hand
    if(root.getVal().compareTo(val) < 0) {
        root.setLeft(add(root.left, val));
    }
    // if it is greater than root's value, set in right hand
    else if(root.getVal().compareTo(val) > 0){
        root.setRight(add(root.right, val));
    }

    return root;
}

暫無
暫無

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

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