二叉树模型matlab实现,利用Matlab实现二叉树的树形显示
接文章《求二叉树的高度以及二叉树的树形显示》,当求出二维矩阵m以后可以借助Matlab绘图更为生动的树形图,如下面的代码所示,将m矩阵赋值给mx,利用下面的程序可以得到比较不错的效果图:
clear all;
clc;
close all;
mx =...
[0 0 0 1 0 0 0
0 1 0 0 0 1 0
1 0 1 0 1 0 0];
cnt = 0;
clear mx;
mx = [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0];
[row,col] = size(mx);
for i = 1:row
for j = 1:col
hold on;
if (mx(i,j) == 1)
plot(j,row-i,'Marker','.','Markersize',30,'MarkerFaceColor','k','MarkerEdgeColor','k');
text(j,row-i-0.05*row,char('A'+cnt));
cnt = cnt + 1;
end
end
end
ylim([-1,row]);
grid on;
d = col + 1;
for i = 1:row-1
% for j = 1:col
% if (mx(i,j) == 1)
% d = j;
% break;
% end
% end
d = d / 2;
for j = 1:col
if (mx(i,j) == 1)
for k = 1:col
if ((mx(i+1,k) == 1) & (abs(k - j) <= floor(d/2)))
hold on;
plot([j,k],[row-i,row-(i+1)],'-k','Linewidth',2.5);
end
end
end
end
end
下面的程序:
#include
#include
#include
using namespace std;
typedef struct BinTreeNode * BinTree;
typedef struct BinTreeNode
{
char data;
BinTree lChild,rChild;
} BinTreeNode;
int max(int a,int b)
{
return a>b?a:b;
}
void BuildBinTree(BinTree *T)
{
char item;
cin>>item;
if(item=='#')
{
*T = NULL;
}
else {
*T = new BinTreeNode;
(*T)->data = item;
BuildBinTree(&((*T)->lChild));
BuildBinTree(&((*T)->rChild));
}
}
int Height(BinTree T)
{
if (!T)
return 0;
return 1 + max(Height(T->lChild),Height(T->rChild));
}
void DestroyBinTree(BinTree *T)
{
if(*T)
{
DestroyBinTree(&((*T)->lChild));
DestroyBinTree(&((*T)->rChild));
delete (*T);
*T = NULL;
}
}
void ShowTreeMarker(int **m,int row,int col,char *s)
{
int cnt = 0;
for(int i=0;i
{
for(int j=0;j
{
if(m[i][j])
cout<
else
cout<
}
cout<
}
}
void MatCreate(int *c,int **m,int level)
{
int i,j;
int start,step;
int len = (1<
m[0][len>>1] = 1;
int d = len;
int cnt = 0;
for(i=1;i
{
//the (i-1)th row
d = d>>1;
start = (d>>1);
//if (c[++cnt])
//m[i][start] = 1;
for(j=1;j<=(1<
if(c[++cnt])
m[i][start+(d+1)*(j-1)] = 1;
}
}
void Pave(BinTree T,int *c,int start)
{
if(T)
{
c[start] = 1;
Pave(T->lChild, c, 2 * start + 1);
Pave(T->rChild, c, 2 * start + 2);
}
}
int main()
{
BinTree T = NULL;
BuildBinTree(&T);
int h = Height(T);
int len = (1<
int *c = new int[len];
memset(c,0,len*sizeof(int));
Pave(T,c,0);
for(int i = 0; i < len; i++)
cout<
cout<
cout<
cout<
int **m = new int*[h];
for(int i= 0;i
m[i] = new int[len];
memset(m[i],0,len*sizeof(int));
}
MatCreate(c,m,h);
for(int i=0;i
{
for(int j=0;j
cout<
cout<
}
ShowTreeMarker(m,h,len,"ABCDEFGHIJK");
DestroyBinTree(&T);
}
的输入为:
ABD##E##CF###
输出图形为:

当输入数据为:
AB#D##CE##FGI###H##输出图形为:

更多推荐



所有评论(0)