1 # include <iostream> 2 using namespace STD; 3 struct treenode // tree struct Definition 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 []) // create a new tree 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) // traverse 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) // The center order traversal 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) // post-order traversal 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) // calculate the number of leaves 57 {58 static int m = 0, n = 0; 59 If (p) // when the tree is not empty 60 {61 m ++; 62
63 countl (p-> lchild); 64 countl (p-> rchild );
66 return m;
69} 70
72} 73 void change (treenode * P) // left and right subtree exchange 74 {75 treenode * r; 76 r = new treenode; 77 int F1 = 0, f2 = 0; 78 If (P = 0) return; // if the tree is empty, 79 if (p-> lchild) 80 {81 change (P-> lchild) exists ); 82 R-> lchild = p-> lchild; 83 F1 ++; // There are left leaves and the symbol bit is not empty 84} 85 if (p-> rchild) 86 {87 change (P-> rchild); 88 R-> rchild = p-> rchild; 89 F2 ++; // has the right leaf, sign bit not blank 90} 91 If (F1 = 0) r-> lchild = NULL; // otherwise, null value is assigned to the intermediate variable 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 <"Please input data in the previous order:"; // enter data as required, in case of empty subtree input * 105 CIN> S; 106 treenode * tree; 107 createbitree (tree, S); 108 cout <"pre-order traversal :"; 109 preorder (tree); // output the result of pre-sequential traversal: 110 cout <Endl; 111 cout <"in-order traversal:"; 112 inorder (tree ); // output 113 cout <Endl; 114 cout <"; 115 aforder (tree ); // output the post-order traversal result 116 cout <Endl; 117 cout <"number of leaves:" <countl (tree) <Endl; // obtain the number of leaves 118 cout <"tree height:" <counth (tree) <Endl; // obtain the tree height 119 change (tree ); // The left and right subtree exchange 120 cout <"the forward traversal after the left and right subtree exchange is:"; 121 preorder (tree ); // output the pre-order traversal result 122 cout <Endl; 123 cout <"the mid-order traversal after the left and right subtree is:"; 124 inorder (tree ); // output the 125 cout result of the forward traversal after the switch <Endl; 126}