返回最低键和最高键之间的差异 - 二叉搜索树

发布于 2024-09-01 11:19:52 字数 544 浏览 0 评论 0原文

这是我正在尝试的关于二叉搜索树的过去考试试卷。我无法检查输出是否正确,因为我无法构建其中之一。

问题在标题中,

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

有人可以建议我需要更改什么才能获得 5/5 分吗:D - 我们唯一要做的就是编写 span 方法,标题已为我们提供。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

太阳哥哥 2024-09-08 11:19:52

您需要定义两个方法,min(Tree)max(Tree),然后span(Tree t)定义为最大值(t)-最小值(t)span 本身不应该是递归的,但如果需要,您可以使 minmax 递归。

请注意,minmax 没有是它们自己的方法。如果您不介意让它们作为自己的单位,您可以将其全部放入 span 中,如下所示:

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

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文