代码之家  ›  专栏  ›  技术社区  ›  Tryer

有没有什么有效的方法来填充一个平衡的树结构

  •  1
  • Tryer  · 技术社区  · 7 年前

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

    节点 0 0 1 那个孩子是对的 2 等等

    请看图片: enter image description here

    树的总深度如下所示: 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;
    

    有没有一种方法可以在数字上有效地填充 tree 使用简单代数的向量大致如下:

    //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算法来计算每个节点的数据结构值。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Damien    7 年前

    对于一个节点 k ,关键点是确定其在图形中的位置,以便确定其父项(如果是左或右子项)。

    然后,k通过对(r[k],p[k])定位

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

    然后通过(r[k]-1,floor(p[k]/2))->节点索引=2^r+p-1

    如果k%2==1,则k是左子级

    我想其余的都很简单