【问题标题】:binary search tree recursive subtree in javajava中的二叉搜索树递归子树
【发布时间】:2010-04-08 02:24:25
【问题描述】:

谁能给我一个代码示例(最好是java)或使用递归返回一个子树的伪代码,该子树包含所有节点,键在fromKey和toKey之间。

因此,如果我要调用 Tree.subtree(5,10),它应该返回 BST 中键在 5 到 10 之间(含 5 到 10)的所有节点——但我不能使用循环或辅助方法……只能递归调用到子树方法,它以fromKey和toKey为参数。

谢谢!

更新:

我尝试了以下不起作用:

public Tree subtree(int from, int to) {
   left.subtree(from, to);
   right.subtree(from, to);
   if (this.key < from || this.key > to) {
      this.delete(this.key);
   }
   return this;   
}

我认为问题在于它返回得太早。我想要做的是遍历树上的每个节点,并删除任何不属于该范围的节点。我在正确的轨道上吗?

【问题讨论】:

    标签: java binary-tree


    【解决方案1】:

    subtree 不应该返回原始树的副本,而不是从中删除键吗?以及您的原始递归如何终止?

    我会推荐这样的东西:

    public static Tree subtreeNullSafe(Tree t, int from, int to) {
       return t == null ? null : t.subtree(from, to);
    }
    
    public Tree subtree(int from, int to) {
       if (this.key > to) {
         return subtreeNullSafe(this.left, from, to);
       } else if (this.key < from) {
         return subtreeNullSafe(this.right, from, to);
       } else {
         // we know that this.key <= to and this.key >= from
         return new Tree(
           this.key,
           subtreeNullSafe(this.left, from, to),
           subtreeNullSafe(this.right, from, to)
         );
       }
    }
    

    这确实使用辅助方法来减少重复。你可以内联null 检查你是否真的被禁止使用。

    【讨论】:

    • 非常感谢!我没有将我的构造函数设置为采用左右树参数 - 只要我在您的解决方案中看到它就点击了。
    猜你喜欢
    • 1970-01-01
    • 2011-07-19
    • 2014-01-02
    • 2021-09-01
    • 2021-07-03
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多