编程题
显示二叉树
### 题目描述
**本题为代码补全填空题,请将题目中给出的源代码补全,并复制到右侧代码框中,选择对应的编译语言(C/Java)后进行提交。若题目中给出的源代码语言不唯一,则只需选择其一进行补全提交即可。复制后需将源代码中填空部分的下划线删掉,填上你的答案。提交后若未能通过,除考虑填空部分出错外,还需注意是否因在复制后有改动非填空部分产生错误。**
排序二叉树的特征是:
某个节点的左子树的所有节点值都不大于本节点值。
某个节点的右子树的所有节点值都不小于本节点值。
为了能形象地观察二叉树的建立过程,小明写了一段程序来显示出二叉树的结构来。
### 源代码
**C**
```c
#include
#include
#define N 1000
#define HEIGHT 100
#define WIDTH 1000
struct BiTree
{
int v;
struct BiTree* l;
struct BiTree* r;
};
int max(int a, int b)
{
return a>b? a : b;
}
struct BiTree* init(struct BiTree* p, int v)
{
p->l = NULL;
p->r = NULL;
p->v = v;
return p;
}
void add(struct BiTree* me, struct BiTree* the)
{
if(the->v < me->v){
if(me->l==NULL) me->l = the;
else add(me->l, the);
}
else{
if(me->r==NULL) me->r = the;
else add(me->r, the);
}
}
//获得子树的显示高度
int getHeight(struct BiTree* me)
{
int h = 2;
int hl = me->l==NULL? 0 : getHeight(me->l);
int hr = me->r==NULL? 0 : getHeight(me->r);
return h + max(hl,hr);
}
//获得子树的显示宽度
int getWidth(struct BiTree* me)
{
char buf[100];
sprintf(buf,"%d",me->v);
int w = strlen(buf);
if(me->l) w += getWidth(me->l);
if(me->r) w += getWidth(me->r);
return w;
}
int getRootPos(struct BiTree* me, int x){
return me->l==NULL? x : x + getWidth(me->l);
}
//把缓冲区当二维画布用
void printInBuf(struct BiTree* me, char buf[][WIDTH], int x, int y)
{
int p1,p2,p3,i;
char sv[100];
sprintf(sv, "%d", me->v);
p1 = me->l==NULL? x : getRootPos(me->l, x);
p2 = getRootPos(me, x);
p3 = me->r==NULL? p2 : getRootPos(me->r, p2+strlen(sv));
buf[y][p2] = '|';
for(i=p1; i<=p3; i++) buf[y+1][i]='-';
for(i=0; ip2) buf[y+1][p3] = '\\';
if(me->l) printInBuf(me->l,buf,x,y+2);
if(me->r) ______________________;
}
void showBuf(char x[][WIDTH])
{
int i,j;
for(i=0; i=0; j--){
if(x[i][j]=='.') x[i][j] = '\0';
else break;
}
if(x[i][0]) printf("%s\n",x[i]);
else break;
}
}
void show(struct BiTree* me)
{
char buf[HEIGHT][WIDTH];
int i,j;
for(i=0; ip2) buf[y+1][p3] = '\\';
if(l!=null) l.printInBuf(buf,x,y+2);
if(r!=null) r.printInBuf(buf,p2+sv.length(),y+2);
}
private int getRootPos(int x){
return l==null? x : x + l.getWidth();
}
}
public class Main
{
public static void main(String[] args)
{
BiTree tree = new BiTree(500);
tree.add(new BiTree(200));
tree.add(new BiTree(509));
tree.add(new BiTree(100));
tree.add(new BiTree(250));
tree.add(new BiTree(507));
tree.add(new BiTree(600));
tree.add(new BiTree(650));
tree.add(new BiTree(450));
tree.add(new BiTree(510));
tree.add(new BiTree(440));
tree.add(new BiTree(220));
tree.show();
}
}
```