If I have a binary search tree S with the number pair (a,b) where (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]).
The runtime restriction is O(h+k), h is the tree height of S, and k is the number of elements within the range.
The classic answer is from "Introduction to Algorithms":
http://staff.ustc.edu.cn/~csli/graduate/algorithms/book6/chap14.htm
Step 1: find a, using the normal binary tree lookup.
Step 2: call tree successor iteratively until you find 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
Related
I would like to perform the Edmond matching algorithm or Blossom algorithm on a Graph (example Graph in picture), but how to I start with a empty matching set?
The Algorithm work this way:
Given: Graph G and matching M in G
Task: find matching M' with |M'| =
[M| + 1, or |M'| = IM| if M maximum
1 let F be the forest consisting of all M-exposed nodes; 2 while there
is outer node x and edge {x, y) with y \in V(F), add (x, y} and
matching edge covering y to F;
3 if there are adjacent outer nodes x, y in same tree, then shrink
cycle (M-blossom) in F \cup {x, y) and go to Step 2;
4 if there are adjacent outer nodes x, y in different trees, then
augment M along M-augmenting path P(x) \cup {x, y} \cup P(y);
5 in reverse order, undo each shrinking and re-establish near-perfect
matchings in blossoms.
You don’t begin the algorithm with an empty M. You have to provide one, generally by generating it with a greedy algorithm that parses all edges e of the graph G and adds each e to M if M + e form a matching.
Give a recursive algorithm btProd which takes as input a binary tree, and outputs
the value that is the product of the numbers contained in the binary tree. If the input is the null tree, then the algorithm should return null.
Algorithm btProd(P)
Require: Input is a tree P
1: btProd(null) ← 0
2: btProd(leaf x) ← x
3: btProd(node L x R) ← btProd(L) + x + btProd(R )
That's the way i would do it but i'm not sure if that's correct
As mentioned in the comments, the product is commutative. Thus, you can traverse the tree in any order you like (pre-,in-,post-order). The recursion you motivated as pseudo-code seems correct, assuming that when you write + x + you mean btProd(L) times btProd(R).
Say I have a balanced binary tree. I wish to search for a key k in the tree. However, if k doesn't exist in the binary tree, it should give me the next greatest number nearest to k.
For examples suppose I have these numbers [1,5,6,8,10] as keys in the tree. If I search for '7' it should return 8 and if I search for 2 it should return 5 etc.
What would have to be the modifications in the binary tree to be able to perform such a search? I want an O(log n) solution as well please.
Assuming you mean "binary search tree" rather than "binary tree", you don't need any modifications to find the minimum element y in the tree such that y >= x.
search(n, x, best_so_far) ::=
if n == nil { return best_so_far }
if n.value == x { return x }
if n.value > x { return search(n.left, x, min(best_so_far, n.value) }
if n.value < x { return search(n.right, x, best_so_far) }
You would call this function as search(root, x, +infinity).
The idea is that if you're exploring the left branch at a node n, you don't need to consider anything to the right of n: n.value is larger than x, and everything to the right is larger than n.value. Similarly, if you're exploring the right branch of a node n, then you can discard everything to the left of n: n.value is smaller than x and everything to the left of n is smaller than n.value.
The code's runtime is bounded by the height of the tree, so is O(log n) if the tree is balanced.
Im studying B tree and in the book they said that:
If the key k is in node x and x is a leaf, delete the key k from x.
If the key k is in node x and x is an internal node, do the following.
a. If the child y that precedes k in node x has at least t keys, then find the predecessor k' of k in the subtree rooted at y. Recursively delete k', and replace k by k' in x. (Finding k' and deleting it can be performed in a single downward pass.)
b. Symmetrically, if the child z that follows k in node x has at least t keys, then find the successor k' of k in the subtree rooted at z. Recursively delete k', and replace k by k' in x. (Finding k' and deleting it can be performed in a single downward pass.)
c. Otherwise, if both y and z have only t- 1 keys, merge k and all of z into y, so that x loses both k and the pointer to z, and y now contains 2t - 1 keys. Then, free z and recursively delete k from y.
My question is this: In case 2.a.
Can someone explain me with example: Recursively delete k', and replace k by k' in x.
Regards.
Suppose you have b tree with the degree t = 4:
26, 49, 60
27,31,34,36 51,55,56,58
Suppose y = [27,31,34,36], x = [51,55,56,58] are not leaf nodes and you want to delete key k = 51. Let K = 49 be the key in the parent node which splits x and y.
Find the predecessor of k which is the rightmost key k' in the subtree y (which could contain integers between 37 and 48 in this example, say k' = 40). Set k = K = 49 and K = k' = 40 and delete k' recursively (which is actually the first case of the deletion procedure when the node is leaf). The resulting b tree looks like
26, 40, 60
27,31,34,36 49,55,56,58
Recently, one of my friends challenged me to solve this puzzle which goes as follows:
Suppose that you have two variables x and y. These are the only variables which can be used for storage in the program. There are three operations which can be done:
Operation 1: x = x+y
Operation 2: x = x-y
Operation 3: y = x-y
Now, you are given two number n1 and n2 and a target number k. Starting with x = n1 and y = n2, is there a way to arrive at x = k using the operations mentioned above? If yes, what is the sequence of operations which can generate x = k.
Example: If n1 = 16, n2 = 6 and k = 28 then the answer is YES. The sequence is:
Operation 1
Operation 1
If n1 = 19, n2 = 7 and k = 22 then the answer is YES. The sequence is:
Operation 2
Operation 3
Operation 1
Operation 1
Now, I have wrapped my head around the problem for too long but I am not getting any initial thoughts. I have a feeling that this is recursion but I do not know what should be the boundary conditions. It would be very helpful if someone can direct me towards an approach which can be used to solve this problem. Thanks!
Maybe not a complete answer, but a proof that a sequence exists if and only if k is a multiple of the greatest common divisor (GCD) of n1 and n2. Let's write G = GCD(n1, n2) for brevity.
First I'll prove that x and y are always integer multiples of the G. This proof is really straightforward by induction. Hypothesis: x = p * G and y = q * G, for some integers p and q.
Initially, the hypothesis holds by definition of G.
Each of the rules respects the induction hypothesis. The rules yield:
x + y = p * G + q * G = (p + q) * G
x - y = p * G - q * G = (p - q) * G
y - x = q * G - p * G = (q - p) * G
Due to this result, there can only be a sequence to k if k is an integer multiple of the GCD of n1 and n2.
For the other direction we need to show that any integer multiple of G can be achieved by the rules. This is definitely the case if we can reach x = G and y = G. For this we use Euclid's algorithm. Consider the second implementation in the linked wiki article:
function gcd(a, b)
while a ≠ b
if a > b
a := a − b
else
b := b − a
return a
This is a repetitive application of rules 2 and 3 and results in x = G and y = G.
Knowing that a solution exists, you can apply a BFS, as shown in Amit's answer, to find the shortest sequence.
Assuming a solution exists, finding the shortest sequence to get to it can be done using a BFS.
The pseudo code should be something like:
queue <- new empty queue
parent <- new map of type map:pair->pair
parent[(x,y)] = 'root' //special indicator to stop the search there
queue.enqueue(pair(x,y))
while !queue.empty():
curr <- queue.dequeue()
x <- curr.first
y <- curr.second
if x == target or y == target:
printSolAccordingToMap(parent,(x,y))
return
x1 <- x+y
x2 <- x-y
y1 <- x-y
if (x1,y) is not a key in parent:
parent[(x1,y)] = (x,y)
queue.enqueue(pair(x1,y))
//similarly to (x2,y) and (x,y1)
The function printSolAccordingToMap() simply traces back on the map until it finds the root, and prints it.
Note that this solution only finds the optimal sequence if one exists, but will cause infinite loop if one does not exist, so this is only partial answer yet.
Consider that you have both (x,y) always <= target & >0 if not you can always bring them in the range by simple operations. If you consider this constraints you can make a graph where there are O(target*target) nodes and edge you can find by doing an operation among three on that node. You now need to evaluate the shortest path from start position node to target node which is (target,any). The assumption here is (x,y) values always stay within (0,target). The time complexity is O(target*target*log(target)) using djikstra.
In the Vincent's answer, I think the proof is not complete.
Let us suppose two relatively prime numbers suppose n1=19 and n2=13 whose GCD will be 1. According to him, sequence exits if k is multiple of GCD.Since every number is multiple of 1. I think it is not possible for every k.