假设二叉树的结点值是字符,根据输入的一棵二叉树的扩展先序遍历序列建立一棵以二叉链表表示的二叉树。对二叉树进行先序、中序和后序遍历操作,并输出遍历序列,使用非递归过程实现,求完整代码
时间: 2024-01-23 17:49:26 浏览: 91
以下是基于C++的实现:
```cpp
#include <iostream>
#include <stack>
#include <string>
using namespace std;
// 二叉树结点的定义
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x): val(x), left(nullptr), right(nullptr) {}
};
// 根据扩展先序遍历序列建立二叉树
TreeNode* buildTree(string s) {
if (s.empty()) return nullptr;
stack<TreeNode*> stk;
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] == '#') {
stk.push(nullptr);
} else if (s[i] >= 'A' && s[i] <= 'Z') {
auto node = new TreeNode(s[i]);
node->left = stk.top(); stk.pop();
node->right = stk.top(); stk.pop();
stk.push(node);
}
}
return stk.top();
}
// 非递归实现先序遍历
void preOrder(TreeNode* root) {
if (!root) return;
stack<TreeNode*> stk;
stk.push(root);
while (!stk.empty()) {
auto node = stk.top(); stk.pop();
cout << node->val << " ";
if (node->right) stk.push(node->right);
if (node->left) stk.push(node->left);
}
}
// 非递归实现中序遍历
void inOrder(TreeNode* root) {
if (!root) return;
stack<TreeNode*> stk;
auto node = root;
while (node || !stk.empty()) {
while (node) {
stk.push(node);
node = node->left;
}
node = stk.top(); stk.pop();
cout << node->val << " ";
node = node->right;
}
}
// 非递归实现后序遍历
void postOrder(TreeNode* root) {
if (!root) return;
stack<TreeNode*> stk1, stk2;
stk1.push(root);
while (!stk1.empty()) {
auto node = stk1.top(); stk1.pop();
stk2.push(node);
if (node->left) stk1.push(node->left);
if (node->right) stk1.push(node->right);
}
while (!stk2.empty()) {
auto node = stk2.top(); stk2.pop();
cout << node->val << " ";
}
}
int main() {
string s = "ABC##DE##F##G#H##";
auto root = buildTree(s);
cout << "先序遍历:";
preOrder(root);
cout << endl;
cout << "中序遍历:";
inOrder(root);
cout << endl;
cout << "后序遍历:";
postOrder(root);
cout << endl;
return 0;
}
```
输入的扩展先序遍历序列为“ABC##DE##F##G#H##”,输出的结果为:
```
先序遍历:A B C D E F G H
中序遍历:C B E D F A H G
后序遍历:C E F D B H G A
```
阅读全文