我成功地通过它的插入方法创建了一个线程二叉搜索树。我现在需要遍历树并按顺序打印。我有有效的代码,但我使用了 boolean 标志来确定我是否已打印该特定节点。对于此分配,它不能是递归的。我想知道是否有一种可能的方法可以将所有 boolean 标志完全清除为 false,因为如果我尝试再次打印它将会并且确实不起作用。有什么建议么?这是我的显示方法的副本。
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();
}
}
最佳答案
您可以使用新的Collections.newSetFromMap( new IdentityHashMap< Node, Boolean >() )
每次都对访问过的节点进行簿记,而不是在 Node
中包含一个标志类本身。
顺便说一句,将 boolean 表达式与常量值进行比较 true
或false
就是很糟糕的风格。例如
while( e == false )
更有效地表达为
while( !e )
关于java - Java 线程二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19885823/