简体   繁体   English

二进制搜索树-搜索范围

[英]Binary Search Tree - Searching for a Scope

If I have a binary search tree S with the number pair (a,b) where (a<=b); 如果我有一个带有数字对(a,b)的二叉搜索树S(a <= b); is there an algorithm that would help me find the elements in S with the key values that are within the range of a,b inclusive ([a,b]). 有没有一种算法可以帮助我找到键值在a,b(含)([a,b])范围内的S中的元素。

The runtime restriction is O(h+k), h is the tree height of S, and k is the number of elements within the range. 运行时限制为O(h + k),h为S的树高,k为范围内的元素数。

The classic answer is from "Introduction to Algorithms": http://staff.ustc.edu.cn/~csli/graduate/algorithms/book6/chap14.htm 经典答案来自“算法简介”: http : //staff.ustc.edu.cn/~csli/graduate/algorithms/book6/chap14.htm

Step 1: find a, using the normal binary tree lookup. 步骤1:使用正常的二叉树查找方法找到一个。

Step 2: call tree successor iteratively until you find b. 步骤2:迭代地调用树后继者,直到找到b。 Tree successor gives you the next item in the tree: 树后继者为您提供树中的下一项:

TREE-SUCCESSOR(x)
  if right[x] ≠ NIL
      then return TREE-MINIMUM (right[x])
  y ← p[x]
  while y ≠ NIL and x = right[y]
      do x ← y
         y ← p[y]
  return y

TREE-MINIMUM (x)
  while left[x] ≠ NIL
      do x ← left[x]
  return x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM