I want to drawing a binary tree with an graphical framework(Qt) like this:
9
/ \
1 10
/ \ \
0 5 11
/ / \
-1 2 6
but I have a problem to set X and Y for every node, do you any idea to setting and fixation position ? (I have only height of every node and left-Child and right-Child)
I was looking for a way to draw binary trees in Qt and I couldn't find an example, so I made a lib to draw binary trees, here it is https://github.com/rom1504/GenericBinaryTree
Your method seems right at first (that's what I did first) but If the last layer isn't full the width of the displayed tree will be too large.
Given the width
canvasWidth
and the heightcanvasHeight
of the canvas you can calculate position of each node.First, let's assign two numbers to each node: the depth of the node and a serial index of the node in fully filled row. In your example, for each node we assign
(depth, index)
asAs @j_random_hacker pointed, we can find the index of a node recursively using this equation:
This can be done using BFS (cost: O(n)). During this traversal let's save also information about the depth of the whole tree
treeDepth
. In our casetreeDepth=3
Then given
canvasWidth
,canvasHeight
andtreeDepth
as global constants, each node's position can be found like this:So in your case positions will be
(canvasHeight/treeDepth*y, canvasWidth*x)
where(y,x)
for every nodeCost: O(n)
Improve the Pavel Zaichenkov's solution,
Let the root's
index
be 1, and for the other node:And the Y would be (consider the depth start from 1):
This algorithm makes that if a node has two childs, then the distance between the node and left-child and the distance between the node and right-child woudl be equal:
I write it in c++ using openframework(http://www.openframeworks.cc/) as a graphical interface.
I've written an article about this very subject. It can be found here: http://adhavoc.com/BinaryTree.html
Essentially, you need to move every child node as left as it can possibly be placed, with the caveat that the child nodes must be left and right of the parent respectively. Then move left branches as far right as possible, with the same caveat.