[英]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**
, 我正在为字符串编写压缩算法,然后应用此加密,例如,原始字符串为
**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,
令
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
. 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. 这种结构很容易保存在二叉树中,但是如何在二叉树的方向上建立反向结构。
You can easily use a simple std::vector for this purpose. 为此,您可以轻松使用简单的std :: vector。 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 } 因此,我宁愿使用std :: vector以“反向”堆形式表示最终结构:初始向量将具有n = 6个元素:{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 } 下一步,您需要进行n-1 = 5次运算,并将和加到向量的末尾,例如:{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 } 下一步4对尾元素的操作:{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. 因此,在(n-1)+(n-2)+(n-3)+ ... + 1 =(n-1)* n / 2运算之后,您将得到相反顺序的树。
By going from right to left, you will traverse your tree in BFS order. 从右到左,您将按照BFS顺序遍历树。
One possible solution could be this 一种可能的解决方案可能是这样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.