triple fault
triple fault

Reputation: 14138

Searching for max value between two 2-3 Tree leafs

I have an 2-3 tree where each leaf consists of:

The tree is ordered by the keys.

I want to find the maximum value between 2 keys i < j (in domain [i,j]), within worst case O(logn).

It is clear to me that I need to store additional information such as "maximum in a subtree". However I can't come up with precise algorithm of going over all relevant subtrees to achieve my goal.

[EDIT] I'm looking for something similar to the following thread:

Search max value between 2 AVL nodes

The only difference is that I'm interested in 2-3 tree.

Upvotes: 1

Views: 373

Answers (2)

Doug Currie
Doug Currie

Reputation: 41200

There is no need to store extra information in the tree nodes.

Each 2-3 node has one or two keys, and 2 to 3 links. Set a variable best_seen to nil. Starting at the root of the tree, consider the following exhaustive cases:

  1. All keys in the node are < i. Recurse to the right. [If there is any key satisfying the criteria, it must be to the right of this node.]

  2. All keys in the node are > j. Recurse to the left. [If there is any key satisfying the criteria, it must be to the left of this node.]

  3. One or both keys are between i and j; choose the larger key between i and j as the best_seen, and recurse to the right of best_seen. [If there is any key larger than best_seen satisfying the criteria, it will be to the right of that key.]

  4. The node is nil, return best_seen

Assertion: best_seen is never replaced with a smaller value. (This is because we always recurse to the right after setting best_seen.)

Upvotes: 0

avim
avim

Reputation: 1019

Keep maxTreeValue in each node, represents the maximum in this sub tree (should be updated after every modification, bottom-up starting from the modified node).

Start searching for both i,j simultaneously, stop at the node where the search paths split.

Search for i from that node. For each node in path, find the maximum between the sub-tree of each edge, from the next edge in i's search path exclusive to the rightmost edge inclusive, or to the edge on the search path of j exclusive, the first between them.

Then do the same symmetrically for j, and return the max between them.

Upvotes: 1

Related Questions