【问题标题】:Implementing a nonrecursive preorder traversal method实现非递归的前序遍历方法
【发布时间】: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


【解决方案1】:

毕竟我想出了一个解决方案。

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 

        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-07-26
    • 2010-12-01
    • 2018-11-11
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2020-09-25
    相关资源
    最近更新 更多