原理:对于数组描述的完全二叉树,序号为i的节点的左右儿子分别为2*i和2*i+1,如果它们不超过数组的元素个数heapSize
利用Graphviz 可视化时,在.dot文件中,输入x->y即可画出x到y的一条有向边
tree.dot文件的示例如下:
digraph tree{ node [style=filled,color=red]; //设置节点属性 edge [color = "black", decorate = false]; //设置边属性 liu80->xu99; liu80->pan94; xu99->ma84; xu99->zhu95; pan94->yang90; pan94->jiang81; ma84->huang89; ma84->zhou94; }
C++代码如下:
void draw() // 利用 Graphviz 可视化输出堆 { ofstream file; string path = "H:/Graphviz/bin/tree.dot"; // "H:/Graphviz/bin/tree.dot" file.open(path); cout << endl << "tree.dot is successfully opened\n\n"; if (file.fail()) { printf("fail to open tree.dot!\n"); return; } else { file << "digraph tree{" << endl; file << "node [style=filled,color=red]; //设置节点属性\n"; file << "edge [color = \"black\", decorate = false]; //设置边属性\n"; for (int i = 1; i <= heapSize; i++) file << heap[i] << ";" << endl; for (int i = 1; i <= heapSize; i++) { if (2*i <= heapSize) { file << heap[i] << "->" << heap[2*i] << ";" << endl; } if (2*i + 1 <= heapSize) file << heap[i] << "->" << heap[2*i + 1] << ";" << endl; } file << "}"; } file.close(); }
运行:
将tree.dot文件放入/bin目录下,在该目录下进入cmd控制台,输入dot -Tpng tree1.dot -o tree1.png命令即可
注意:中文乱码问题
解决方案见
https://www.jianshu.com/p/6d9bbbbf38b1
一个可视化示例图如下图所示: