2014-04-30 5 views
0

나는이 코드의 대부분을 내 교수가 받았다. 우리는 이진 트리의 높이를 계산하기위한 재귀 적 방법을 코딩하고 테스트하도록 요청 받았다. 여기 내 등급 클래스객체로 이진 트리의 높이를 얻는다

public int height(TreeNode root) 
{ 
    if(root == null) 
    { 
     return 0; 
    } 
    else 
    { 
     return 1 + Math.max(height(root.lc), 
     height(root.rc)); 
    } 
} 



public class MainBinaryTreeWithLNRTraversal 
{ 
    public static void main(String[] arg 
    { 
     BinaryTreeWithLNRTraversal t = new BinaryTreeWithLNRTraversal(); 

     Listing l; 
     Listing l1 = new Listing("Ann", "1st Avenue", "111 1111"); 
     Listing l2 = new Listing("Bill",  "2nd Avenue", "222 2222"); 
     Listing l3 = new Listing("Carol", "3rd Avenue", "333 3333"); 
     Listing l4 = new Listing("Mike", "4th Avenue", "444 4444"); 
     Listing l5 = new Listing("Pat",  "5th Avenue", "555 5555"); 
     Listing l6 = new Listing("Sally", "6th Avenue", "666 6666"); 
     Listing l7 = new Listing("Ted",  "7th Avenue", "777 7777"); 
     Listing l8 = new Listing("Vick", "8th Avenue", "888 8888"); 
     Listing l9 = new Listing("Will", "9th Avenue", "999 9999"); 
     Listing l10 = new Listing("Zack", "11th Avenue", "101 0101"); 
     Listing l11 = new Listing("Zeek", "12th Avenue", "121 2121"); 
     System.out.println("Tyler Hansen \n"); 
     // insert the nodes 
     t.insert(l9); 
     t.insert(l7); 
     t.insert(l10); 
     t.insert(l2); 
     t.insert(l8); 
     t.insert(l1); 
     t.insert(l4); 
     t.insert(l3); 
     t.insert(l6); 
     t.insert(l5); 
     //Output all the nodes in NLR left tree then right tree order 
     t.showAll(); 
     t.height(); 
    } 
} 

나는 무엇을 높이 괄호에 넣어야할지 모른다. 어떤 도움이나 힌트를 주시면 대단히 감사하겠습니다. 필요한 경우 더 많은 코드를 제공 할 수 있습니다.

답변

0

t의 루트 노드로 height()으로 전화해야합니다.

당신이 BinaryTreeWithLNRTraversal에 대한 정의를 포함하지 않았기 때문에, 나는 그것이이 함께 할 수있는 뭔가가 가정 : 트리의 루트 노드를 얻을 수있는 공용 접근이 없기 때문에 https://github.com/DavidSchirduan/ClassProjects/blob/master/CSCI230-java2/Assignment4/BinarySearchTree.java

, 코드는 다음과 같이됩니다 : 클래스 및 BinaryTreeWithLNRTraversal는 동일한 패키지에있는 경우

System.out.println(height(t.root)); 

이 작동합니다. 그렇지 않으면 BinaryTreeWithLNRTraversal에 대한 코드를 수정하거나 교수님에게 루트 노드를 가져 오기위한 공용 접근을 포함하도록 요청해야합니다.