要求:
- 孩子兄弟链表存储二叉树
- 输入二叉树
- 凹入表法输出树
- 求树中叶子节点的个数
- 求树中最大度的节点(没写)
- 求树的深度
- 求根到某节点的路径
输入:
0
1
3
-1
-1
4
5
-1
-1
6
-1
-1
2
7
-1
-1
8
-1
-1
输出:
0(root)
1(left)
3(left)
4(right)
5(left)
6(right)
2(right)
7(left)
8(right)
**********
leavesnumber:5
**********
depth:4
Please enter destination:
2
Path:
0
2
--------------------------------
Process exited with return value 0
Press any key to continue . . .
代码:
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 40
typedef struct TNode{
int data;
struct TNode *left,*right;
}TNode,*Tree;
TNode* createTree(){
TNode* p;
int data;
printf("Please enter:\n");
scanf("%d",&data);
if(data==-1){
p=NULL;
}else{
p=(TNode*)malloc(sizeof(TNode));
p->data=data;
p->left=createTree();
p->right=createTree();
}
return p;
}
void DispTree(TNode* b)
{
TNode* stack[MaxSize],* p;
int level[MaxSize][2], top, i, n, width = 4;
char* type;
if (b != NULL)
{
top = 1;
stack[top] = b;
level[top][0] = width;
level[top][1] = 2;
while (top > 0)
{
p = stack[top];
n = level[top][0];
switch (level[top][1])
{
case 0:
type = "left";
break;
case 1:
type = "right";
break;
case 2:
type = "root";
break;
}
for (i = 1; i <= n; i++)
printf(" ");
printf("%d(%s)\n",p->data,type);
top--;
if (p->right != NULL)
{
top++;
stack[top] = p->right;
level[top][0] = n + width;
level[top][1] = 1;
}
if (p->left != NULL)
{
top++;
stack[top] = p->left;
level[top][0] = n + width;
level[top][1] = 0;
}
}
}
}
int getLeavesNum(TNode* p){
if(p==NULL){
return 0;
}
if(p->left==NULL && p->right==NULL){
return 1;
}
int ln=getLeavesNum(p->left);
int rn=getLeavesNum(p->right);
return (ln+rn);
}
int getDepth(TNode* p){
if(p==NULL) return 0;
int ld=getDepth(p->left);
int rd=getDepth(p->right);
return (ld>rd? ld+1 : rd+1);
}
int stack[MaxSize];
int top=0;
void getPath(TNode* p,int des){
int flag=top-1;
if(top>0&&stack[flag]==des){
printf("**********\nPath:\n");
for(int i=0;i<top;i++){
printf("%d\n",stack[i]);
}
top=0;
return ;
}
if(p== NULL){
return ;
}
stack[top++]=p->data;
getPath(p->left,des);
getPath(p->right,des);
top--;
}
void printPath(TNode* p){
int des=-1;
printf("Please enter destination:\n");
scanf("%d",&des);
getPath(p,des);
}
int main(){
TNode* root=createTree();
DispTree(root);
printf("**********\nleavesnumber:%d\n",getLeavesNum(root));
printf("**********\ndepth:%d\n",getDepth(root));
printPath(root);
return 0;
}