标签:long dtree play splay one hid tac src data
1 #include <bits/stdc++.h> 2 #define null NULL 3 #define maxn 500005 4 5 typedef long long ll; 6 7 using namespace std; 8 9 typedef struct tree//二叉树的定义 10 { 11 char data; 12 tree *left; 13 tree *right; 14 }tree,*netree; 15 16 //创建一个先序二叉树 17 netree createtree() 18 { 19 char c; 20 cin >> c; 21 netree root; 22 if(c == ‘#‘) root = null; 23 else 24 { 25 root = new tree; 26 root -> data = c; 27 root -> left = createtree(); 28 root -> right = createtree(); 29 } 30 return root; 31 } 32 33 //输出递归先序二叉树 34 void pretree(netree root) 35 { 36 if(root) 37 { 38 cout << root -> data << " "; 39 pretree(root -> left); 40 pretree(root -> right); 41 } 42 } 43 44 //输出递归中序二叉树 45 void midtree(netree root) 46 { 47 if(root) 48 { 49 midtree(root -> left); 50 cout << root -> data << " "; 51 midtree(root -> right); 52 } 53 } 54 55 //输出递归后序二叉树 56 void endtree(netree root) 57 { 58 if(root) 59 { 60 endtree(root -> left); 61 endtree(root -> right); 62 cout << root -> data << " "; 63 } 64 } 65 66 //层次遍历 67 void every(netree root) 68 { 69 queue<netree> q; 70 if(root) 71 { 72 q.push(root); 73 while(!q.empty()) 74 { 75 netree p; 76 p = q.front(); 77 q.pop(); 78 cout << p -> data << " "; 79 if(p -> left)q.push(p -> left); 80 if(p -> right)q.push(p -> right); 81 } 82 } 83 } 84 85 void mid_tree(netree root) 86 { 87 stack<netree>s; 88 while(!s.empty() || root) 89 { 90 if(root) 91 { 92 s.push(root); 93 root = root -> left; 94 } 95 else 96 { 97 netree p; 98 p = s.top(); 99 s.pop(); 100 cout << p -> data << " "; 101 root = p -> right; 102 } 103 } 104 105 } 106 107 int main() 108 { 109 netree root; 110 111 cout << "请输入一个先序的二叉树(以#为空)来建立二叉树" << endl; 112 root = createtree(); 113 114 cout << "二叉树的递归先序遍历是" <<endl; 115 pretree(root); 116 cout << endl; 117 118 cout << "二叉树的递归中序遍历是" <<endl; 119 midtree(root); 120 cout << endl; 121 122 cout << "二叉树的递归后序遍历是" <<endl; 123 endtree(root); 124 cout << endl; 125 126 cout << "二叉树的层次遍历是" <<endl; 127 every(root); 128 cout << endl; 129 130 cout << "二叉树的非递归中序遍历是" <<endl; 131 mid_tree(root); 132 cout << endl; 133 } 134 135 /* 136 A## 137 ABC#### 138 AB##C## 139 ABCD###EF##G##H## 140 A##B## 141 */
标签:long dtree play splay one hid tac src data
原文地址:https://www.cnblogs.com/WINDZLY/p/9978393.html