我需要实现一个前序遍历方法。遍历节点的二叉树。
我试图找出解决以下问题的方法。我知道如何实现这样的方法,但问题是我不能偏离老师给我的规则。这使得这项练习变得更加困难。
这些是规则:
- 老师禁止使用递归
- 我必须使用堆栈
- 从根节点开始
有关其他限制,请参阅我的代码中的注释。
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 } } }
我希望有人可以帮助我解决这个问题。