tree编程
发布时间: 2024-05-22 19:07:18
① C++: 缂栧啓绋嫔簭锛屽垱寤轰竴涓浜屽弶镙戙傚疄鐜扮粺璁′簩鍙夋爲鍙跺瓙缁撶偣镄勪釜鏁板拰浜屽弶镙戠殑娣卞害
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedefintElemType;//鏁版嵁绫诲瀷
//瀹氢箟浜屽弶镙缁撴瀯锛屼笌鍗曢摼琛ㄧ浉浼硷纴澶氢简涓涓鍙冲╁瓙缁撶偣
typedefstructBiTNode{
ElemTypedata;//鏁版嵁锘
structBiTNode*lChild,*rChlid;//宸﹀彸瀛愭爲锘
}BiTNode,*BiTree;
//鍏埚簭鍒涘缓浜屽弶镙
intCreateBiTree(BiTree*T)
{
ElemTypech;
ElemTypetemp;
scanf("%d",&ch);
temp=getchar();
if(ch==-1)
*T=NULL;
else
{
*T=(BiTree)malloc(sizeof(BiTNode));
if(!(*T))
exit(-1);
(*T)->data=ch;
printf("杈揿叆%d镄勫乏瀛愯妭镣癸细",ch);
CreateBiTree(&(*T)->lChild);
printf("杈揿叆%d镄勫彸瀛愯妭镣癸细",ch);
CreateBiTree(&(*T)->rChlid);
}
return1;
}
//鍏埚簭阆嶅巻浜屽弶镙
voidTraverseBiTree(BiTreeT)
{
if(T==NULL)
return;
printf("%d",T->data);
TraverseBiTree(T->lChild);
TraverseBiTree(T->rChlid);
}
//涓搴忛亶铡嗕簩鍙夋爲
voidInOrderBiTree(BiTreeT)
{
if(T==NULL)
return;
InOrderBiTree(T->lChild);
printf("%d",T->data);
InOrderBiTree(T->rChlid);
}
//钖庡簭阆嶅巻浜屽弶镙
voidPostOrderBiTree(BiTreeT)
{
if(T==NULL)
return;
PostOrderBiTree(T->lChild);
PostOrderBiTree(T->rChlid);
printf("%d",T->data);
}
//浜屽弶镙戠殑娣卞害
intTreeDeep(BiTreeT)
{
intdeep=0;
if(T)
{
intleftdeep=TreeDeep(T->lChild);
intrightdeep=TreeDeep(T->rChlid);
deep=leftdeep>=rightdeep?leftdeep+1:rightdeep+1;
}
returndeep;
}
//姹备簩鍙夋爲鍙跺瓙缁撶偣涓鏁
intLeafcount(BiTreeT,int&num)
{
if(T)
{
if(T->lChild==NULL&&T->rChlid==NULL)
num++;
Leafcount(T->lChild,num);
Leafcount(T->rChlid,num);
}
returnnum;
}
//涓诲嚱鏁
intmain(void)
{
BiTreeT;
BiTree*p=(BiTree*)malloc(sizeof(BiTree));
intdeepth,num=0;
printf("璇疯緭鍏ョ涓涓缁撶偣镄勫,-1琛ㄧず娌℃湁鍙剁粨镣: ");
CreateBiTree(&T);
printf("鍏埚簭阆嶅巻浜屽弶镙: ");
TraverseBiTree(T);
printf(" ");
printf("涓搴忛亶铡嗕簩鍙夋爲: ");
InOrderBiTree(T);
printf(" ");
printf("钖庡簭阆嶅巻浜屽弶镙: ");
PostOrderBiTree(T);
printf(" ");
deepth=TreeDeep(T);
printf("镙戠殑娣卞害涓:%d",deepth);
printf(" ");
Leafcount(T,num);
printf("镙戠殑鍙跺瓙缁撶偣涓鏁颁负:%d",num);
printf(" ");
return0;
}
② 求java图形界面树类编程源码举例。类似windows资源管理器那样的。如附图,2层2项即可。
publicvoidinit(){
ContainercontentPane=null;
=newDefaultMutableTreeNode("我的电脑");
1=newDefaultMutableTreeNode("网络");
2=newDefaultMutableTreeNode("硬盘");
1_1=newDefaultMutableTreeNode("无限");
1_2=newDefaultMutableTreeNode("有限");
2_1=newDefaultMutableTreeNode("A");
2_2=newDefaultMutableTreeNode("B");
treeNode.add(treeNode1);
treeNode.add(treeNode2);
treeNode1.add(treeNode1_1);
treeNode1.add(treeNode1_2);
treeNode2.add(treeNode2_1);
treeNode2.add(treeNode2_2);
JTreetree=newJTree(treeNode);
contentPane=getContentPane();
JPaneljp=newJPanel();
jp.add(tree);
contentPane.add(jp);
this.setSize(300,250);
this.setLocation(400,300);
this.setVisible(true);
}
热点内容