我需要实现一个preorder遍历方法。遍历节点的二叉树。
我试图找出下面问题的解决方案。 我知道如何实现这样的方法,但问题是我不能偏离老师给我的规则。这使得这项练习变得更加困难。
这些是规则:
请参阅我的代码中的注释以了解其他限制。
public class Node {
int key;
String name;
Node leftChild;
Node rightChild;
public Node(int key, String name){
this.key = key;
this.name = name;
}
// prints information about a certain node
public void visitStap(){
System.out.println("Node name : " + this.name );
System.out.println("Node value : " + this.key + "\n");
}
}
public void preOrderTraverseTreeNonRecursive(){
Node current = this.root; // Begin at the root Node
Stack<Node> theStack = new Stack<Node>();
// extra code is allowed here
while(!theStack.empty() || current != null){
// extra code is allowed here
if(current != null){
// only 3 lines of code allowed
}else{
// only 2 lines of code allowed
}
}
}
我希望有人可以帮我解决这个问题。
答案 0 :(得分:0)
毕竟我想出了一个解决方案。
public void preOrderTraverseTreeNonRecursive(){
Node current = this.root; // Begin bij de root
Stack<Node> theStack = new Stack<Node>();
while(!theStack.empty() || current != null){
if(current != null){
// only 3 lines of code allowed
current.visitStap(); // print current Node information
theStack.push(current); // push current Node on to the stack
current = current.leftChild; // set current node to leftChild
}else{
// only 2 lines of code allowed
current = theStack.pop().rightChild; // pop Node from stack and
// get its rightChild
}
}
}