hws
hws

Reputation: 41

A method to print a binary search tree (BST) from the largest element to the smallest

I think I have to modify one of the traversals. I tried modifying one that print from the smallest to the largest which is this one

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

But it didn't work. I'm still stuck on what I should try next. This the binary search tree I'm using:

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;
    }

Upvotes: 3

Views: 4383

Answers (2)

Scarl
Scarl

Reputation: 950

All you have to do it swap the llink and rlink. To print the tree from largest to smallest, you can use one of the trees traversal methods. for example, the one that suits this case is the Inorder traversal because it prints the tree from smallest to largest in terms of values. All you have to do is the following:

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

That should print it from largest to smallest.

Upvotes: 0

Hakan Serce
Hakan Serce

Reputation: 11256

The code you have posted looks OK for sorting from smallest to largest.

If you want to sort the other way around, then the following code should work:

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

Upvotes: 2

Related Questions