分别写出二叉树的先序遍历,中序遍历和后序遍历的非递归算法。(给出完整的c++代码
时间: 2024-12-16 20:28:20 浏览: 4
当然可以。以下是二叉树的三种遍历(先序、中序和后序)的非递归算法实现,使用了栈的数据结构:
```cpp
#include <iostream>
#include <stack>
// 二叉树节点结构体
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 先序遍历(根-左-右)
void preorderTraversal(TreeNode* root) {
if (root == nullptr) return;
std::stack<TreeNode*> stack; // 使用栈保存待访问的节点
stack.push(root);
while (!stack.empty()) {
TreeNode* current = stack.top();
std::cout << current->val << " ";
stack.pop(); // 出栈当前节点
if (current->right) stack.push(current->right); // 先右
if (current->left) stack.push(current->left); // 后左
}
}
// 中序遍历(左-根-右)
void inorderTraversal(TreeNode* root) {
if (root == nullptr) return;
std::stack<TreeNode*> stack;
TreeNode* lastVisited = nullptr;
while (root != nullptr || !stack.empty()) {
while (root != nullptr) {
stack.push(root);
root = root->left;
}
root = stack.top();
stack.pop();
std::cout << root->val << " ";
lastVisited = root;
root = root->right;
}
}
// 后序遍历(左-右-根)
void postorderTraversal(TreeNode* root) {
if (root == nullptr) return;
std::stack<TreeNode*> stack1, stack2; // 两个栈用于存储待处理节点
stack1.push(root);
while (!stack1.empty()) {
TreeNode* current = stack1.top();
stack1.pop();
stack2.push(current); // 将当前节点压入辅助栈
if (current->left) stack1.push(current->left);
if (current->right) stack1.push(current->right);
}
while (!stack2.empty()) {
std::cout << stack2.top()->val << " ";
stack2.pop();
}
}
// 测试
int main() {
// 创建一个测试二叉树...
// ...
preorderTraversal(root); // 打印先序遍历结果
std::cout << "\n";
inorderTraversal(root); // 打印中序遍历结果
std::cout << "\n";
postorderTraversal(root); // 打印后序遍历结果
return 0;
}
```
阅读全文