数据结构作业:二叉树的相关运算
用递归的方法实现以下算法:
1.以二叉链表表示二叉树,建立一棵二叉树;
2.输出二叉树的先序、中序和后序遍历结果;
3.计算二叉树的深度;
4.统计二叉树的结点个数;
5.统计二叉树的叶结点个数;
6.统计二叉树的度为1的结点个数;
7.输出二叉树中从每个叶子结点到根结点的路径。
1 #include<bits/stdc++.h> 2 #define maxsize 100 3 using namespace std; 4 5 //节点结构 6 struct tree 7 { 8 char data; 9 struct tree* lchild; 10 struct tree* rchild; 11 }; 12 13 //创建二叉树 14 void create(tree* &root) 15 { 16 char value; 17 cin>>value; 18 if(value=='/')//结点为空 19 return; 20 root=(tree*)malloc(sizeof(tree)); 21 root->data=value; 22 root->lchild=NULL; 23 root->rchild=NULL; 24 create(root->lchild); 25 create(root->rchild); 26 27 } 28 29 //递归先序 30 void preorder(tree* root) 31 { 32 if(root!=NULL) 33 { 34 cout<<root->data; 35 preorder(root->lchild); 36 preorder(root->rchild); 37 } 38 } 39 40 //递归中序 41 void inorder(tree* root) 42 { 43 if(root!=NULL) 44 { 45 inorder(root->lchild); 46 cout<<root->data; 47 inorder(root->rchild); 48 } 49 } 50 51 //递归后序 52 void postorder(tree* root) 53 { 54 if(root!=NULL) 55 { 56 postorder(root->lchild); 57 postorder(root->rchild); 58 cout<<root->data; 59 } 60 } 61 62 //计算二叉树层数 63 int depth(tree* root) 64 { 65 int llen,rlen; 66 if(root==NULL) return 0; 67 else 68 { 69 llen=depth(root->lchild)+1; 70 rlen=depth(root->rchild)+1; 71 } 72 if(llen>rlen) return llen; 73 return rlen; 74 } 75 76 //统计结点个数 77 int numnode(tree* root) 78 { 79 if(root==NULL) return 0; 80 else return numnode(root->lchild)+numnode(root->rchild)+1; 81 } 82 83 //统计叶节点个数 84 void leaf(tree* root,int &count) 85 { 86 if(root) 87 { 88 if(root->lchild==NULL&&root->rchild==NULL) 89 count+=1; 90 leaf(root->lchild,count); 91 leaf(root->rchild,count); 92 } 93 } 94 95 //统计度为1的结点个数 96 int duis1(tree* root) 97 { 98 if(root==NULL) return 0; 99 int cnt=0; 100 if((root->lchild==NULL&&root->rchild!=NULL)||(root->rchild==NULL&&root->lchild!=NULL)) 101 cnt++; 102 cnt+=duis1(root->lchild); 103 cnt+=duis1(root->rchild); 104 return cnt; 105 } 106 107 void route(tree* root,char *path,int pathlen) 108 { 109 if(root==NULL) return; 110 if(root->lchild==NULL&&root->rchild==NULL) 111 { 112 cout<<endl<<root->data<<" "; 113 for(int i = pathlen-1; i >= 0; i--) 114 cout<<path[i]<<" "; 115 } 116 else 117 { 118 path[pathlen++]=root->data; 119 route(root->lchild,path,pathlen); 120 route(root->rchild,path,pathlen); 121 } 122 } 123 124 int main() 125 { 126 int sum=0; 127 char path[100]; 128 tree* root=(tree*)malloc(sizeof(tree)); 129 cout<<"请先序输入:"; 130 create(root);//建树 131 leaf(root,sum);//叶节点个数 132 cout<<"先序序列输出结果为:"; 133 preorder(root); 134 cout<<'\n'; 135 cout<<"中序序列输出结果为:"; 136 inorder(root); 137 cout<<'\n'; 138 cout<<"后序序列输出结果为:"; 139 postorder(root); 140 cout<<'\n'; 141 cout<<"深度为:"<<depth(root)<<endl; 142 cout<<"结点个数为:"<<numnode(root)<<endl; 143 cout<<"叶结点个数为:"<<sum<<endl; 144 cout<<"度为1的结点个数为:"<<duis1(root)<<endl; 145 cout<<"Route:"; 146 route(root,path,0); 147 return 0; 148 }