[英]How to print my binary tree in order
我相信我的inOrderTraverseTree()
方法將樹按順序排列,但我不確定如何按順序實際打印樹。 有什么建議么? 為什么該方法不能按原樣打印出來? 謝謝,扎克
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;
}
}
}
該錯誤在addNode()的這一行中:
if(line.compareTo(focusNode.line) == -1){
.
.
更改為:
if(line.compareTo(focusNode.line) < 0){
.
.
在此處查看有關返回值的更多詳細信息:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo%28java.lang.String%29
和
其余的代碼對我來說看起來不錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.