문제

This is a past exam paper on binary search trees I am attempting. I have no way to check if the output is correct as I am not capable of building one of these things.

The question is in the title

class Tree{
    Tree left;
    Tree right;
    int key;

   public static int span(Tree tree)
   {
        if ( tree == null ){
             return null;
        }

        if( tree.left != null)
             int min = span(tree.left);
         }

        if( tree.right != null){
             int max = span(tree.right);
         }
         return max - min;
    }
}

Could anyone suggest what I need to change to get 5/5 marks :D - the only thing we have to do is write the span method, the header was given for us.

도움이 되었습니까?

해결책

You need to define two methods, min(Tree) and max(Tree), then span(Tree t) is defined as max(t) - min(t). span itself shouldn't be recursive, but you can make min and max recursive if you want.

Note that min and max doesn't have to be their own methods. If you don't care for making them stand as their own units, you can put it all into span like this:

int span(Tree t) {
   Tree tMin = t;
   while (tMin.left != null) {
      tMin = tMin.left;
   }

   Tree tMax = t;
   while (tMax.right != null) {
      tMax = tMax.right;
   }

   return tMax.key - tMin.key;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top