I have to draw a presentable tree using CFTree
. You can see in picture
The should satisfy all principles stated in this link.
The principle are :
Principle 1: The edges of the tree should not cross each other.
Principle 2: All nodes at the same depth should be drawn on the same horizontal line. This helps make clear the structure of the tree.
Principle 3: Trees should be drawn as narrowly as possible.
Principle 4: A parent should be centered over its children.
Principle 5: A subtree should be drawn the same no matter where in the tree it lies.
Principle 6: The child nodes of a parent node should be evenly spaced.
How should I calculate X,Y position of each nodes?
You can solve this problem recursively.
Without diagrams (which would help a lot!) here goes an outline - you need to fill in the details! - of one algorithm for this. The algorithm is being typed directly into the answer - expect errors.
First:
Now:
Consider first drawing a single node with no children. Based on your desired size you can determine a bounding box for this single node. You are using circles so the anchor, the (0,0) coordinate origin of the bounding box is at the centre and the bounding box is +/- the radius relative to that. So you have the bounding box's anchor, (0,0), and its size relative to that - say (x minimum, x maximum, y minimum, y maximum) being (-radius, +radius, -radius, +radius). You will probably also wish to store the node's label. So for example for the "L" node in your diagram in total you have a representation (i.e. and object) containing: (0,0), (-radius, +radius, -radius, +radius) & "L".
Now consider drawing a node with a single child. By a recursive call determine the bounding box for the child. Construct a bounding box to enclose the child with your node at the top centre of this box and the child bounding box directly below it. So you have the bounding box's anchor, it's size relative to that, and a single child at an offset from the anchor. So for example for the "H" node above you have: (0,0), (xmin, xmax, ymin, ymax), "H", 1 child at (xoffset, yoffset), child is (a reference to the object) (0,0), (-radius, +radius, -radius, +radius) & "L".
Now consider drawing a node with 2 children, etc.
A single recursive traversal from the root of your tree, at each node combining the information returned from subtrees, produces a structure describing the layout of your tree. Now draw it!
HTH