algorithm - 设置绘制二叉树的位置

标签 algorithm tree drawing binary-tree drawing2d

我想用这样的图形框架 (Qt) 绘制二叉树:

        9
       /  \
      1    10
    /  \     \
   0    5     11
  /    /  \
 -1   2    6

但是我在为每个节点设置 X 和 Y 时遇到问题,您知道设置和固定位置吗? (我只有每个节点的高度和左 child 和右 child )

最佳答案

给定 Canvas 的宽度 canvasWidth 和高度 canvasHeight,您可以计算每个节点的位置。

首先,让我们为每个节点分配两个数字:节点的深度 和节点在完全填充的行中的序列索引。在您的示例中,对于每个节点,我们将 (depth, index) 分配为

          (0, 1)
         /      \
     (1, 1)      (1, 2)
     /   \            \
 (2, 1)  (2, 2)      (2, 4)
 /       /     \
(3, 1)  (3, 3) (3, 4)

As @j_random_hacker pointed, we can find the index of a node recursively using this equation:

leftChildIndex = parentIndex * 2 - 1
rightChildIndex = parentIndex * 2

这可以使用 BFS 来完成(成本:O(n))。在此遍历期间,让我们还保存有关整棵树 treeDepth 深度的信息。在我们的例子中 treeDepth=3

然后给定canvasWidthcanvasHeighttreeDepth作为全局常量,每个节点的位置可以这样找到:

def position(depth, index):
    x = index * canvasWidth / (2^depth + 1)
    y = depth * canvasHeight / treeDepth
    return y, x

因此在您的情况下位置将是 (canvasHeight/treeDepth*y, canvasWidth*x) 其中每个节点的 (y,x)

           (0, 1/2)
         /          \
     (1, 1/3)       (1, 2/3)
     /      \            \
 (2, 1/5)   (2, 2/5)      (2, 4/5)
 /           /     \
(3, 1/9) (3, 3/9)  (3, 4/9)

成本:O(n)

关于algorithm - 设置绘制二叉树的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14184655/

相关文章:

algorithm - 索引 csv 文件中的列

java - 无法获取 k-ary 树的叶子数

cocoa - NSButtonCell 子类的按钮类型不起作用

java - 从给定角度计算目标像素

algorithm - 查找预排序数组中的两个元素总和是否等于某个值

c++ - 向链表中添加新值

algorithm - 指定不存在子项的前序遍历的二叉树

javascript - 如何比较两个不同的javascript对象的相同属性(不比较实例函数)

c# - WPF C#设计题中绘制图表

java - 如何使用 pivot 作为最左边的键对其进行排序?