按先序遍历序列创建一个二叉树的二叉链表,并按先序遍历、中序遍历、后序遍历将其输出。
测试用例1node
-+a##*b##c##/d##e##↵
期待输出1ios
前序遍历结果:- + a * b c / d e ↵ 中序遍历结果:a + b * c - d / e ↵ 后序遍历结果:a b c * + d e / - ↵
#include <iostream> #include <list> #include <string> using namespace std; struct tree { char data; tree* left; tree* right; tree() :left(NULL),right(NULL) {} }; string str; int curIndex; void CreateTree(tree* node); void PreorderOutput(tree* node); void SequentialOutput(tree* node); void PostSequenceOutput(tree* node); int main() { cin >> str; tree* root = new tree; CreateTree(root); cout << "前序遍历结果:"; PreorderOutput(root); cout << endl; cout << "中序遍历结果:"; SequentialOutput(root); cout << endl; cout << "后序遍历结果:"; PostSequenceOutput(root); cout << endl; return 0; } void CreateTree(tree* node) { node->data = str[curIndex++]; if (node->left == NULL && curIndex < str.size()) { if (str[curIndex] == '#') { curIndex++; } else { node->left = new tree; CreateTree(node->left); } } if (node->right == NULL && curIndex < str.size()) { if (str[curIndex] == '#') { curIndex++; } else { node->right = new tree; CreateTree(node->right); } } } void PreorderOutput(tree* node) { cout << node->data<<" "; if (node->left != NULL) { PreorderOutput(node->left); } if (node->right != NULL) { PreorderOutput(node->right); } } void SequentialOutput(tree* node) { if (node->left != NULL) { SequentialOutput(node->left); } cout << node->data << " "; if (node->right != NULL) { SequentialOutput(node->right); } } void PostSequenceOutput(tree* node) { if (node->left != NULL) { PostSequenceOutput(node->left); } if (node->right != NULL) { PostSequenceOutput(node->right); } cout << node->data << " "; }