1 #include <iostream> 2 using namespace std; 3 const int N = 9; 4 int order[1 << N], k = 0; 5 struct TreeNode { 6 int val; 7 TreeNode *leftChild; 8 TreeNode *rightChild; 9 TreeNode() : TreeNode(0) {} 10 TreeNode(int x) : val(x), leftChild(nullptr), rightChild(nullptr) {} 11 }; 12 int number; 13 void createBinaryTree(TreeNode *&root) 14 { 15 16 cin >> number; 17 if (number == -1) 18 return; 19 root = new TreeNode(number); 20 createBinaryTree(root->leftChild); 21 createBinaryTree(root->rightChild); 22 } 23 24 void preOrderTraverse(TreeNode *root, int order[], int *k) { 25 if (root == nullptr) 26 return; 27 order[(*k)++] = root->val; 28 preOrderTraverse(root->leftChild, order, k); 29 preOrderTraverse(root->rightChild, order, k); 30 } 31 32 void inOrderTraverse(TreeNode *root, int order[], int *k) 33 { 34 if (root == nullptr)return; 35 inOrderTraverse(root->leftChild, order, k); 36 order[(*k)++] = root->val; 37 inOrderTraverse(root->rightChild, order, k); 38 } 39 40 void postOrderTraverse(TreeNode *root, int order[], int *k) 41 { 42 if (root == nullptr)return; 43 postOrderTraverse(root->leftChild, order, k); 44 45 postOrderTraverse(root->rightChild, order, k); 46 order[(*k)++] = root->val; 47 } 48 void print() 49 { 50 for (int i = 0; i < k; i++) 51 { 52 if (i == 0) 53 cout << order[i]; 54 else 55 cout << " " << order[i]; 56 } 57 cout << endl; 58 } 59 int main() 60 { 61 TreeNode *root = nullptr; 62 createBinaryTree(root); 63 64 65 66 preOrderTraverse(root, order, &k); 67 68 print(); 69 k = 0; 70 inOrderTraverse(root, order, &k); 71 72 print(); 73 k = 0; 74 postOrderTraverse(root, order, &k); 75 76 print(); 77 return 0; 78 } 79