4

トラバーサルの 1 つを変更する必要があると思います。最小から最大まで印刷するものを変更してみましたが、これはこれです

private void printTree(BinaryTreeNode t) {
    if (t != null) {
        printTree(t.llink);
        System.out.print(" " + t.info);
        printTree(t.rlink);
    }
}

しかし、うまくいきませんでした。次に何を試すべきか、まだ悩んでいます。これは私が使用している二分探索木です:

public class BinarySearchTree extends BinaryTree {
    //Default constructor.
    //Postcondition: root = null;

    public BinarySearchTree() {
        super();
    }

    //Copy constructor.
    public BinarySearchTree(BinarySearchTree otherTree) {
        super(otherTree);
    }

public class BinaryTree {

    //Definition of the node
    protected class BinaryTreeNode {

        DataElement info;
        BinaryTreeNode llink;

        public DataElement getInfo() {
            return info;
        }

        public BinaryTreeNode getLlink() {
            return llink;
        }

        public BinaryTreeNode getRlink() {
            return rlink;
        }
        BinaryTreeNode rlink;
    }

    protected BinaryTreeNode root;

    //Default constructor
    //Postcondition: root = null;
    public BinaryTree() {
        root = null;
    }

    //Copy constructor
    public BinaryTree(BinaryTree otherTree) {
        if (otherTree.root == null) //otherTree is empty.
        {
            root = null;
        }
        else {
            root = copy(otherTree.root);
        }
    }

    public BinaryTreeNode getRoot() {
        return root;
    }
4

2 に答える 2

2

投稿したコードは、最小から最大への並べ替えに問題ないようです。

逆に並べ替えたい場合は、次のコードが機能するはずです。

private void printTree(BinaryTreeNode t) {
        if (t != null) {
            printTree(t.rlink);
            System.out.print(" " + t.info);
            printTree(t.llink);
        }
    }
于 2012-05-25T17:11:02.097 に答える
0

llink と rlink を交換するだけです。ツリーを最大から最小の順に出力するには、ツリー トラバーサル メソッドのいずれかを使用できます。たとえば、このケースに適しているのは、ツリーを最小値から最大値の順に出力するため、Inorder トラバーサルです。あなたがしなければならないのは、次のことだけです。

if(t!=null){        
    printTree(t.rlink);
    System.out.print(" " + t.info);
    printTree(t.llink);
}

それはそれを最大から最小に印刷するはずです。

于 2014-01-17T05:59:20.287 に答える