-1

事前注文トラバーサル メソッドを実装する必要があります。ノードのバイナリ ツリーのトラバース。

以下の問題の解決策を見つけようとしています。私はそのような方法を実装する方法を知っていますが、問題は、先生から与えられた規則から逸脱できないことです。これにより、この演習はかなり難しくなります。

これらはルールです:

  • 先生は再帰の使用を禁止した
  • スタックを使用する必要があります
  • ルート ノードから開始
  • 他の制限については、コード内のコメントを参照してください。

    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
            }
        }
    }
    

誰かがこの問題で私を助けてくれることを願っています。

4

1 に答える 1

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 

        }
    }
}
于 2016-02-19T14:37:36.983 に答える