【发布时间】:2016-02-19 14:10:49
【问题描述】:
我需要实现一个前序遍历方法。遍历节点的二叉树。
我正在尝试找出解决以下问题的方法。 我知道如何实现这样的方法,但问题是我不能偏离老师给我的规则。这使得这项练习变得更加困难。
这些是规则:
- 老师禁止使用递归
- 我必须使用堆栈
- 从根节点开始
-
请参阅我的代码中的 cmets 了解其他限制。
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 } } }
我希望有人可以帮助我解决这个问题。
【问题讨论】:
-
请注意,您有
Node current = this.root;,但没有定义名为root的字段。 -
“preOrderTraverseTreeNonRecursive”方法位于另一个名为 binaryTree 的类中。我没有包括那个课程。我只是从那个类中取出了这个方法。
标签: java binary-tree tree-traversal preorder non-recursive