-1

im learning algorithms atm and i have a question how can i increase all keys values who's bigger or equal to K by D in red-black tree in O(lgn)

Assume the red-black tree has n nodes called S

INCREASE-FROM(S,K,D)

dor
  • 25
  • 1
  • 7

2 Answers2

0

A binary search tree has the property that for a given node all nodes in the left sub-tree will be smaller then the node and all nodes in the right sub tree will be larger. So lets assume the root has value K. Then every node in the right sub tree needs to be increased which since the tree is balanced (red black tree) will contain about half the nodes. Thus you need to perform n/2 increase operations or O(n) operations

So what you're asking for is not possible

Mitch
  • 3,342
  • 2
  • 21
  • 31
  • well buddy it sure possible i see this question in a test that i should take soon its something tricky for sure there is a clue thats says "maybe save the difference between two nodes" – dor Jun 29 '18 at 13:41
  • @dor better yet consider a tree where all nodes are `>= k` how do you expect to visit `n` nodes in `log n` time – Mitch Jun 29 '18 at 17:05
  • @dor No, it is not possible. Is it possible that there is more to the question than what you posted? Is that the *exact* question? – Jim Mischel Jun 30 '18 at 00:44
0

This can be done if the values in the tree is additive to its parent. Take this tree from wikipedia

Traditional red-black tree from wikipedia

So 13 is the parent, the 17 would then be 17-13=4, the 15 would be 15-17=-1. This means that when you need the real value you would need to sum the parent nodes, so to get to 15 you take 13 -> 4 -> -2 13+4-2=15.

That way you can modify the nodes that are greater than x in log n time.

If we wanted to modify all greater than 23 with +4, we go down to 17, then to 25, which is > 23 and add 4 to its relative value which was 25-17=8 and increase it to 12, now all its children are 4 larger, then we go to 22, which is smaller so we subtract 4 from its relative value of -3, which then gets -7 and as we have reaches the button we are done. So what is the value of the node which originally was 27, its 13+4+(8+4)+2=31.

But I'd not want to write the code to rebalance the tree when a node is added or deleted.

Surt
  • 15,501
  • 3
  • 23
  • 39
  • But if in the tree above you wanted to increase all that are greater than 8 by 12, then the node that currently has the value of 11 will now have the value 19, which makes it larger than the root. So the tree would have to be re-balanced. – Jim Mischel Jul 03 '18 at 03:20
  • @JimMischel that is correct, but that should only cost log N which keeps the operation at log N. – Surt Jul 03 '18 at 05:08