数据结构树的前序、中序、后序遍历,树叶数量,左右子树交换实现代码

  1 #include <iostream>
  2 using namespace std;
  3 struct TreeNode          //树结构体定义
  4 {
  5     char data;
  6     TreeNode *lchild,*rchild;
  7 };
  8 char getonech(char ar[])
  9 {    static int i;
 10 return ar[i++];
 11 }
 12 void CreateBiTree(TreeNode *&p,char ar[])       //建立一个新树
 13 {  
 14     char ch;
 15     ch=getonech(ar);
 16     if(ch!='*')
 17     {     
 18             p=new TreeNode;
 19          p->data=ch;
 20          CreateBiTree(p->lchild,ar);
 21          CreateBiTree(p->rchild,ar);
 22     }
 23     else p=NULL;
 24 }
 25 
 26 void preorder(TreeNode *p)          //前序遍历
 27 {  
 28     if(p!=NULL)
 29     { 
 30         cout<<p->data;               
 31         preorder(p->lchild);      
 32         preorder(p->rchild);
 33     }
 34 }
 35 
 36 void inorder(TreeNode *p)           //中序遍历
 37 {
 38     if (p) 
 39     {
 40         inorder(p->lchild);    
 41         cout<<p->data;
 42         inorder (p->rchild);
 43     }    
 44 } 
 45 
 46 void aforder(TreeNode *p)            //后序遍历
 47 {
 48     if (p) 
 49     {
 50         aforder(p->lchild);
 51         aforder(p->rchild);
 52         cout<<p->data;
 53     }    
 54 } 
 55 
 56 int countl(TreeNode *p)           //计算树叶数量
 57 {
 58     static int m=0,n=0;
 59     if(p)                      //树不空时
 60     {
 61         m++;
 62        
63 countl(p->lchild); 64 countl(p->rchild);
66 return m;
69
} 70
72 } 73 void change(TreeNode *p) //左右子树交换 74 { 75 TreeNode *r; 76 r=new TreeNode; 77 int f1=0,f2=0; 78 if(p==0) return ; //树为空时,跳出 79 if(p->lchild) 80 { 81 change(p->lchild); 82 r->lchild=p->lchild; 83 f1++; //有左叶子,符号位不为空 84 } 85 if(p->rchild) 86 { 87 change(p->rchild); 88 r->rchild=p->rchild; 89 f2++; //有右叶子,符号位不为空 90 } 91 if(f1==0) r->lchild=NULL; //否则,给中间变量赋空值 92 if(f2==0) r->rchild=NULL; 93 if(f1||f2) 94 { 95 p->rchild=r->lchild; //左右子树交换 96 p->lchild=r->rchild; 97 } 98 } 99 100 void main() 101 { 102 char *s; 103 s=new char[100]; 104 cout<<"请以前序方式输入数据:"; //按要求输入数据,遇空子树输入* 105 cin>>s; 106 TreeNode *tree; 107 CreateBiTree(tree,s); 108 cout<<"前序遍历为:"; 109 preorder(tree); //输出前序遍历结果 110 cout<<endl; 111 cout<<"中序遍历为:"; 112 inorder(tree); //输出中序遍历结果 113 cout<<endl; 114 cout<<"后序遍历为:"; 115 aforder(tree); //输出后序遍历结果 116 cout<<endl; 117 cout<<"叶子数为:"<<countl(tree)<<endl; //求出叶子数 118 cout<<"树高为:"<<counth(tree)<<endl; //求出树高 119 change(tree); //左右子树交换 120 cout<<"左右子树交换后的前序遍历为:"; 121 preorder(tree); //输出交换后前序遍历结果 122 cout<<endl; 123 cout<<"左右子树交换后的中序遍历为:"; 124 inorder(tree); //输出交换后中序遍历结果 125 cout<<endl; 126 }
原文地址:https://www.cnblogs.com/2011winseu/p/3132700.html