user1886376
user1886376

Reputation:

How to build a binary tree from the leaves to the root

how to build a binary tree from the leaves to the root of that is the reverse direction. I am writing a compression algorithm for strings and xor apply this encryption, for example we have the original string as **44**333**55**555**4**333**,

Let xo = 44, x1 = 333, x2 = 55, x3 = 555, x4 = 4, x5 = 333 <=> **x0**x1**x2**x3**x4**x5,

Applying this algorithm we obtain:

x01 = x0 xor x1, x23 = x2 xor x3, x45 = x4 xor x5 <=> **x01**x23**x45**

Again,

x0123 = x01 xor x23 and x012345 = x0123 xor x23 .

This structure is easy to hold in a binary tree, but how to build a reverse in the direction of a binary tree.

Upvotes: 0

Views: 3533

Answers (2)

kdurga
kdurga

Reputation: 97

One possible solution could be this

  1. Make treenodes of all given values and put them in a queue.
  2. Pop first element from queue name it FIRST. 2.1 pop next element from queue and name it as SECOND. if not present break. 2.2 create a node TEMP treenode(which is XOR of FIRST and SECOND ). 2.3 Make FIRST and SECOND as children of TEMP. 2.4 Push TEMP into queue. 2.5 repeat steps from 2 until queue has only one element.
  3. Mark first as root.

Upvotes: 0

SGrebenkin
SGrebenkin

Reputation: 572

You can easily use a simple std::vector for this purpose. If you recall how the heap is being built in heapsort, you will figure out the structure easily. This won't be actually the original heap, but this kind of binary tree representation can be very helpful.

So, I would rather represent the final structure in the "reverse" heap form using std::vector: The initial vector will be of n=6 elements: { 44, 333, 55, 555, 4, 333 }

The next step you make n-1=5 operations and add the sums to the end of the vector like: { 44, 333, 55, 555, 4, 333, 44333, 33355, 55555, 5554, 4333 }

The next step 4 operations with the tail elements: { 44, 333, 55, 555, 4, 333, 44333, 33355, 55555, 5554, 4333, 4433333355, 3335555555, 555555554, 55544333 }

So, after (n - 1) + (n - 2) + (n - 3) + ... + 1 = (n - 1) * n / 2 operations you will get your tree in reverse order.

By going from right to left, you will traverse your tree in BFS order.

Upvotes: 1

Related Questions