用C++写二叉树的遍历
时间: 2023-10-15 07:04:33 浏览: 74
二叉树_C++_二叉树遍历_Vc_
5星 · 资源好评率100%
二叉树的遍历分为三种:前序遍历、中序遍历和后序遍历。
以下是使用C++实现二叉树遍历的示例代码:
```c++
#include <iostream>
#include <stack>
using namespace std;
// 定义二叉树节点
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// 前序遍历
void preorderTraversal(TreeNode* root) {
if (root) {
cout << root->val << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}
// 中序遍历
void inorderTraversal(TreeNode* root) {
if (root) {
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
}
// 后序遍历
void postorderTraversal(TreeNode* root) {
if (root) {
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->val << " ";
}
}
// 非递归前序遍历
void preorderTraversalNonRecursive(TreeNode* root) {
stack<TreeNode*> s;
TreeNode* p = root;
while (p || !s.empty()) {
if (p) {
cout << p->val << " ";
s.push(p);
p = p->left;
} else {
p = s.top();
s.pop();
p = p->right;
}
}
}
// 非递归中序遍历
void inorderTraversalNonRecursive(TreeNode* root) {
stack<TreeNode*> s;
TreeNode* p = root;
while (p || !s.empty()) {
if (p) {
s.push(p);
p = p->left;
} else {
p = s.top();
s.pop();
cout << p->val << " ";
p = p->right;
}
}
}
// 非递归后序遍历
void postorderTraversalNonRecursive(TreeNode* root) {
stack<TreeNode*> s;
TreeNode* p = root;
TreeNode* lastVisitedNode = nullptr;
while (p || !s.empty()) {
if (p) {
s.push(p);
p = p->left;
} else {
TreeNode* topNode = s.top();
if (topNode->right && topNode->right != lastVisitedNode) {
p = topNode->right;
} else {
cout << topNode->val << " ";
s.pop();
lastVisitedNode = topNode;
}
}
}
}
int main() {
// 构建二叉树
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
// 测试遍历算法
cout << "前序遍历结果:";
preorderTraversal(root);
cout << endl;
cout << "中序遍历结果:";
inorderTraversal(root);
cout << endl;
cout << "后序遍历结果:";
postorderTraversal(root);
cout << endl;
cout << "非递归前序遍历结果:";
preorderTraversalNonRecursive(root);
cout << endl;
cout << "非递归中序遍历结果:";
inorderTraversalNonRecursive(root);
cout << endl;
cout << "非递归后序遍历结果:";
postorderTraversalNonRecursive(root);
cout << endl;
return 0;
}
```
阅读全文