c++ - 是否有任何有效的方法来填充平衡树结构

标签 c++ algorithm tree binary-tree

我有一个平衡的二叉树结构:

节点 0 在深度 0 是根。 根的左 child 是1,右 child 是2,依此类推。

请看图片:enter image description here

树的总深度为 N。此 N 是问题的唯一参数。 N 层的节点被指定为叶节点。

我正在使用以下节点结构存储这棵树。

struct node_s{
    int n, depth, parent;//n is node number
    int nodescendents;//number of descendents of the current node
    std::vector<int> descendents;//Descendents in ascending order
    int lchild, rchild;//Immediate left child and right child
    std::vector<int> lchildleaves;//leaf nodes that descend from the immediate 
                                                      //left child
    std::vector<int> rchildleaves;//leaf nodes that descend from the immediate 
                                                      //right child
};

我打算将树本身存储为:

std::vector<node_s> tree;

有没有一种方法可以使用简单的代数以数字方式有效地填充 vector ,大致如下:

//Creating the nth node, beginning from 0th node, then 1st node and so on
nodes_s node;
//populate all data structures of the nth node
//precisely, here, there are loops, algebraic calculations, etc., that can help 
//populate all of the node_s data members.
tree.push_back(node);

目前我能想到的唯一方法是显式构建一个图并运行某种 Dijkstra 算法来计算每个节点的这些数据结构值。

最佳答案

对于节点k,关键点是识别它在图中的位置,以便识别它的父节点,它是左 child 还是右 child 。

对于节点k,它的秩r[k]等于floor(log2(k+1)),它在秩中的位置等于p[k] = k - 2^r[k] + 1

则k由对(r[k], p[k])定位

相反,k = 2^r[k] + p[k] - 1

然后它的父节点位于 (r[k]-1, floor(p[k]/2)) -> node index = 2^r + p - 1

如果 k%2 == 1,则 k 是左 child

我想剩下的很简单

关于c++ - 是否有任何有效的方法来填充平衡树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53349791/

相关文章:

python - 寻找一种有效的方法或算法来检查文件是否属于某个文件夹路径列表中的某个项目

c++ - 为什么 boost::asio::io_service 不能用 std::bind 编译?

c++ - sizeof(size_t) == sizeof(void*) 总是正确的吗?

algorithm - pageranking算法如何处理没有出站链接的网页?

algorithm - 生成具有 k 个的二进制字符串序列,其中下一个字符串有两位不同

algorithm - 图与 BFS 和 DFS 树的等价性

c++ - 我如何找出 std::istream 中有多少字节可用?

c++ - Qt 使用自定义图标创建快捷方式

algorithm - 谁来写生成坐标的函数

c - BST 二叉树删除 C 中值 = 0 的叶子的函数