[英]How to print my binary tree in order
I believe my inOrderTraverseTree()
method puts the tree in order but I'm not sure how to go about actually printing it in order like that. 我相信我的inOrderTraverseTree()
方法将树按顺序排列,但我不确定如何按顺序实际打印树。 Any suggestions? 有什么建议么? And why does the method not print them out in order as it is? 为什么该方法不能按原样打印出来? Thanks, Zach 谢谢,扎克
public class Tree
{
Node root;
public static void main(String[] args){
Tree t = new Tree();
t.addNode("hey");
t.addNode("fghjk");
t.addNode("aaaaaa");
t.addNode("zzzzzz");
t.addNode("egh");
t.addNode("rrrrrr");
t.inOrderTraverseTree(t.root);
}
public void displayTree(){
Node link = root;
while(link != null){
}
}
public void addNode(String line){
//Create a new Node and initialize it
Node newNode = new Node(line);
//If there is no root this becomes root
if(root == null){
root = newNode;
} else {
//Set root as the Node we will start
//with as we traverse the tree
Node focusNode = root;
// Future parent for our new Node
Node parent;
while(true){
// root is the top parent so we start there
parent = focusNode;
//Check if the new Node should go on the left
//side of the parent node
if(line.compareTo(focusNode.line) == -1){
focusNode = focusNode.leftChild;
//If the left child has no children
if(focusNode == null){
parent.leftChild = newNode;
return; //All Done
}
} else { // If we get here put the node on the right
focusNode = focusNode.rightChild;
//If the right child has no children
if(focusNode == null){
//then place the node on the right of it
parent.rightChild = newNode;
return; //All Done
}
}
}
}
}
public void inOrderTraverseTree(Node focusNode)
{
if(focusNode != null){
//traverse the left node
inOrderTraverseTree(focusNode.leftChild);
//Visit the currently focused on node
System.out.println(focusNode);
//Traverse the right node
inOrderTraverseTree(focusNode.rightChild);
}
}
class Node {
String line;
Node leftChild;
Node rightChild;
Node(String line){
this.line = line;
}
//this method overrides toString in Object class
public String toString(){
return line;
}
}
}
The bug is in this line of addNode(): 该错误在addNode()的这一行中:
if(line.compareTo(focusNode.line) == -1){
.
.
Change it to: 更改为:
if(line.compareTo(focusNode.line) < 0){
.
.
See more details on the return value here: 在此处查看有关返回值的更多详细信息:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo%28java.lang.String%29 http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo%28java.lang.String%29
and 和
String Compareto actual return value 字符串比较到实际返回值
The rest of the code looks good to me. 其余的代码对我来说看起来不错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.