How to dynamically change nodes of a binary tree visually

I worked with the following code: http://bl.ocks.org/NPashaP/7683252 . This is a graphical representation of a tree. I removed most of the code (graceful labels) by only allowing two nodes per parent and changing the data structure to an array.

The only problem left now is repositioning. The original code does it perfectly. But since I want a binary tree, I allowed the user to insert the left or right child. The reposition source code will animate the first child directly from the parent, but that would be wrong in a binary tree. I want him to either go left or right.

reposition = function (v) {
    function repos(v) {
        var lC = getLeafCount(v.v),
            left = v.p.x; //parent x-position

        v.c.forEach(function (d) {
            var vc = d; //saving reference of the child in parent object
            d = tree.getVerticeById(d.v); //actually fetching the child object
            var w = 0;
            if(d.d == 'right') { w += 15 * lC }
            if(d.d == 'left') { w -= 15 * lC }
            d.p = {x: left + w, y: v.p.y + tree.h}; //setting the position
            vc.p = d.p; //setting the child pos in parent obj
            repos(d);
        });
    }
    repos(v[0]);
};

      

Some parts of my code differ from the original code because I changed the data structure as stated earlier. I have tried to comment on the parts that can be misleading, but the mathematics of repositioning is important.

This code worked well at first ( https://i.stack.imgur.com/gjzOq.png ). But after some testing, I found a huge repositioning issue: nodes crash with each other ( https://i.stack.imgur.com/pdQfy.png )!

Conclusion: I tried to modify the original function to keep in mind the left and right arrangement of the nodes, but I couldn't do it. I wrote this variation of the method that does, but it still has some problems as shown in the pictures. I would appreciate some input on this.

+3


source to share


1 answer


In the end I quickly solved this problem.



After running the reposition function posted in the question, I ran another function that fixed the issue. The new function goes through all levels of the tree and checks if the nodes are too close to each other. If they are, the algorithm finds the closest common ancestor and increases the distance between its left and right children. After that, there are no more collisions between nodes.

0


source







All Articles