比如,如果你要生成以下一个树: a / \ b c / \ / \ d e f g 可以用以下程序初始化,测试前序,中序,后序输出: #include <iostream> struct Node { char val; struct Node* left; struct Node* right; Node(int v) : val(v), left(NULL), right(NULL) {} }; struct Node* init() { struct Node* root; root = new struct Node('a'); root->left = new struct Node('b'); root->right = new struct Node('c'); root->left->left = new struct Node('d'); root->left->right = new struct Node('e'); root->right->left = new struct Node('f'); root->right->right = new struct Node('g'); return root; } // 测试前序输出 void preorder_output(const struct Node* root) { if (root == NULL) return ; std::cout << root->val << "\t"; preorder_output(root->left); preorder_output(root->right); } // 测试中序输出 void inorder_output(const struct Node* root) { if (root == NULL) return ; inorder_output(root->left); std::cout << root->val << "\t"; inorder_output(root->right); } // 测试后序输出 void postorder_output(const struct Node* root) { if (root == NULL) return ; postorder_output(root->left); postorder_output(root->right); std::cout << root->val << "\t"; } int main() { struct Node* root = init(); std::cout << std::endl << "前序输出:"; preorder_output(root); std::cout << std::endl << "中序输出:"; inorder_output(root); std::cout << std::endl << "后序输出:"; postorder_output(root); return 0; }
比如,如果你要生成以下一个树:
可以用以下程序初始化,测试前序,中序,后序输出: