2016-10-30 8 views
0

재귀 메서드가 자체를 호출하는 횟수를 저장하는 방법을 알 수 없습니다. 어떤 사람이 올바른 방향으로 나를 가리킬 수 있다면 크게 감사하겠습니다! 아래 코드는 내 코드가 잘못되었다고 생각하는 부분에 대한 의견이 있습니다.재귀 메서드가 자체적으로 이진 트리를 사용하여 호출하는 횟수를 저장하는 방법

package module8_auriemma_assignment; 
import java.util.*; 

public class fibonacciTree{ 

Node root; 

public void addNode(int key, int num) { 
    Node newNode = new Node(key, num); 

    if (root == null) { 
     root = newNode; 
    } 
      else { 
     Node focusNode = root; 
     Node parent; 
     while (true) { 
      parent = focusNode; 
      if (key < focusNode.key) { 
       focusNode = focusNode.leftChild; 
       if (focusNode == null) { 
        parent.leftChild = newNode; 
        return; 
       } 
      } 
          else 
          { 
       focusNode = focusNode.rightChild;   
       if (focusNode == null) { 
        // then place the new node on the right of it 
        parent.rightChild = newNode; 
        return; // All Done 
       } 

      } 

     } 
    } 

} 



public static void main(String[] args) { 



    fibonacciTree theTree = new fibonacciTree(); 

    Scanner input = new Scanner (System.in); 

     System.out.println("Please enter an index"); 
     System.out.println("I will compute your index's Fibonacci numbers."); 
     System.out.println("I will compute numbers that do not exceed a billion"); 

     int number; 

     int key; 
     key = 0; 

     for(number = input.nextInt(); number < 1000000; number++){ 


      System.out.println(fibonacci(number));       
      theTree.addNode(key, number); 

      /* 
      I am not sure if I should be adding a new node everytime the 
      loop happens in the main class OR if I should be having it store 
      a node inside of the fibonacci method itself 
      */ 

      number++; 
      key++; 

      } 

        } 

public static long fibonacci(int i) 
{ 

      if (i == 0) return 0; 
    if (i <= 2) return 1; 

    long fibTerm = fibonacci(i - 1) + fibonacci(i - 2); 

    if(fibTerm > 1000000000){ 
      System.out.println("Number too large"); 

       System.exit(0); 
      } 
      else{ 
       return fibTerm; 

      } 
       return fibTerm; 
} 
} 

.

package module8_auriemma_assignment; 
class Node { 
int key; 
int num; 

Node leftChild; 
Node rightChild; 

Node(int key, int num) { 

    this.key = key; 
    this.num = num; 

} 


    @Override 
public String toString() { 

    return num + " has the key " + key; 



} 

} 
+0

힌트 : 우리가 당신을 돕기 위해 우리 시간을 보냈 으면합니다. 따라서 입력 코드의 형식을 올바르게 지정하는 데 몇 분 정도 시간을 할애하십시오! 사용할 수있는 "미리보기"기능도 있습니다. 진지하게 : 나는 당신이 방금 그런 혼란을 우리에게 던 졌다고 생각했을 때 나는 당신의 질문에 답하는 것에 완전히 관심을 잃었다. 그런 다음 자바 코딩 스타일 가이드를 공부하고 싶다. 클래스 이름은 UpperCase를 시작합니다. 항상. – GhostCat

답변

0

fibonacci(int i)은 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + ...

용액의 시리즈로 감소 될 때까지 자신을 호출 유지 메소드가 호출 된 횟수입니다. 호출 된 횟수를 알고 싶다면 반환 값을 살펴보십시오.

관련 문제