算法导论的C实现——画出d叉树
前几天写了一个画出二叉树的函数: 算法导论的C实现——画出二叉树。
章后有一道题是有关d叉树的,记得后面几章也会有用到d叉树的地方,就把画二叉树的函数稍改了下,现在可以画出d叉树。
d叉树空格的计算原理和二叉树很相近,比如现在有一棵高度为 的d叉树。当 从树根向树叶递增时,可以算出第 行两个节点之间的空格的数目:
可以得到每一行两元素间的空格数:
code
如下:
//myUtil.cpp
//draw a d fork tree
//AGRS: A[]:需要画树的数组
// size:数组的长度
// dFork:d叉树的宽度
void drawDTREE(int A[], int size, int dFork)
{
int height = lgd(dFork, size);
printf("The height of this tree is: %d\n", height);
int numRow;
int startBlank = 0;
int intervalBlank = 0;
int subscript = 0;
int tempLength;
int k_ele;
int k_base;
//自上而下
for(int iDraw=0; iDraw<height; iDraw++)
{
numRow = static_cast<int>(pow(dFork, iDraw));
if(height-iDraw>1)
{
k_base = static_cast<int>(pow(dFork, height-iDraw-1));
k_ele = k_base-1;
intervalBlank = k_ele*dforkElementInterval+k_base*dforkBaseInterval;
startBlank = (intervalBlank-dforkElementInterval-dforkBaseInterval+1)/2;
}
else
{
startBlank = 0;
intervalBlank = dforkBaseInterval;
}
//画此行第一个元素前面的空格
for(int iBlank=0; iBlank<startBlank; iBlank++){printf(" ");}
//输出此行第一个元素
printf("%d", A[subscript]);
subscript++;
//画接下来的空格组+元素
for(int iCouple=0; iCouple<numRow-1;iCouple++)
{
tempLength = get_digit(A[subscript-1]);
if(subscript<size)
{
for (int iBlank=0; iBlank<intervalBlank-tempLength+1; iBlank++){printf(" ");}
printf("%d", A[subscript]);
subscript++;
}
}
//换行
printf("\n");
}
}
//myUtil.h
#define lgd(d,x) static_cast<int>(ceil(log((d-1)*x+1)/log(d)))
#define dforkBaseInterval 7
#define dforkElementInterval 1
void testDFORKTREE();
void drawDTREE(int A[], int size, int dFork);
测试函数如下所示:
//testDFORKTREE
void testDFORKTREE()
{
int dFork = 3;
int testArray[12] = {15, 1, 9, 5, 2, 8, 7, 4, 6, 6, 5, 3};
HEAP A = {sizeof(testArray)/ sizeof(testArray[0]), sizeof(testArray)/ sizeof(testArray[0]), testArray};
drawDTREE(A.Array, A.array_size, dFork);
}
当改变dFork
的值的时候,画出来的d叉树如下所示:
Draw 2 fork tree
The height of this tree is: 4
15
1 9
5 2 8 7
4 6 6 5 3
Draw 3 fork tree
The height of this tree is: 3
15
1 9 5
2 8 7 4 6 6 5 3
Draw 4 fork tree
The height of this tree is: 3
15
1 9 5 2
8 7 4 6 6 5 3