简体   繁体   中英

Threaded Binary Search Tree Java

I have managed to create a threaded binary search tree through it's insertion method. I now need to traverse the tree and print in order. I have code that works, but I used an boolean flag to determine whether or not I have printed that specific node. For this assignment it must not be recursive. I was wondering if there is a possible way to completely clear all of the boolean flags to false, because if I try to print again it will, and does, not work. Any suggestions? here is the copy of my display method.

public void display(){
    Node parent=top;
    Node current=top;
    while (current != null){
        parent = current;
        current = current.getLeft();
    }
    System.out.println(parent);
    current=parent.getRight();
    while(current!= null){
        while(current.isHasLeftThread()==false && current.getLeft().hasBeenHere()==false){
            parent = current;
            current=current.getLeft();
        }
        System.out.println(current);
        current.setBeenHere(true);
        current=current.getRight();
        System.out.println(current);
        current.setBeenHere(true);
        current = current.getRight();
    }
}

You can use a fresh Collections.newSetFromMap( new IdentityHashMap< Node, Boolean >() ) to do the bookkeeping for visited nodes every time rather than including a flag in the Node class itself.

Incidentally, comparing Boolean expressions to the constant values true or false is just awful style. For example

while( e == false )

is much more effectively expressed as

while( !e )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM