java中的二叉搜索树递归子树

时间:2010-04-08 02:24:26

标签: java binary-tree

任何人都可以指向一个代码示例(最好是java)或psuedocode,它使用递归来返回包含所有带有fromKey和toKey之间键的节点的子树。

因此,如果我要调用Tree.subtree(5,10),它应该返回BST中包含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;   
}

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

1 个答案:

答案 0 :(得分:3)

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检查你是否真的禁止使用它。