最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Adding the nodes into correct levels vector of a Binary_Tree class - Stack Overflow

programmeradmin0浏览0评论

I am trying to create a Binary_Tree class implementation. The nodes themselves are Binary_Trees. Each Binary_Tree has a vector<vector<Binary_Tree<T>*>*> *levels where each inner vector represents a level's nodes(so the first inner vector is always having 1 element which is the root itself). Each Binary_Tree also has a size_t *level that is basically the level index of that node, so the main root is always going to be at level zero, while its direct children are 1 but its children's children are 2 and so on. Imagine the tree below:

     A
   /   \
  B     C
 / \   / \
D   E F   G
 \       /
  H     I
 /
J

The level variable for each node is depended on their distance from A. So B's is 1, D's is 2 and J's is 4.

I have a function that is called whenever a node is either created or added, if created, the both parameters are the same, but when added, the first paremeter is the node that its levels vector is about to be updated, and the second parameter is the node that is about to be added to the vector in the correct inner vector. I have come this far:

        void updateLevels(Binary_Tree<T>* tree, Binary_Tree<T> *p) {
            if (tree->levels->size() < *p->level+1) tree->levels->push_back(new vector<Binary_Tree<T>*>());
            tree->levels->at(*p->level)->push_back(p);
        }

on one side, it works perfect if tree is A, and the reason is, that the level variable is depended on A. But if tree is for example B and p is D, meaning D is being added to B's levels at the index 1(because in B's levels D should be at the second inner vector), it doesn't work.

This is the logic behind adding nodes to the left(the addRight is similar):

        Binary_Tree<T> *addLeft(T item) {
            if (left) {
                left->root = new T(item);
                return left;
            }
            left = new Binary_Tree<T>(item, this, false);
            *left->level+=*level+1;
            Binary_Tree<T> *t = this;
            while (t) {
                ++*t->size;
                updateLevels(t, left);
                updateLeaves(t, this, false);
                t = t->parent;
            }
            return left;
        }

And this is an example of how i use this function:

tree->addLeft('B');
tree->left->addLeft('D');

so you can see that each add function is called from a different node.

I know that i need to find a rythm in when to add a new vector(level) to the tree's levels vector, and where to add the node depending on the tree, but i cannot figure out the pattern. How can i go about this?

发布评论

评论列表(0)

  1. 暂无评论