请你用c++编写程序对二叉树进行遍历,要求实现递归前序、中序、后序遍历和非递归前序、中序、后序遍历
时间: 2023-08-05 14:10:35 浏览: 120
好的,我可以为您提供 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 preOrderTraversalRecursion(TreeNode* root) {
if(root == nullptr) {
return;
}
cout << root->val << " ";
preOrderTraversalRecursion(root->left);
preOrderTraversalRecursion(root->right);
}
// 递归中序遍历
void inOrderTraversalRecursion(TreeNode* root) {
if(root == nullptr) {
return;
}
inOrderTraversalRecursion(root->left);
cout << root->val << " ";
inOrderTraversalRecursion(root->right);
}
// 递归后序遍历
void postOrderTraversalRecursion(TreeNode* root) {
if(root == nullptr) {
return;
}
postOrderTraversalRecursion(root->left);
postOrderTraversalRecursion(root->right);
cout << root->val << " ";
}
// 非递归前序遍历
void preOrderTraversalIterative(TreeNode* root) {
stack<TreeNode*> st;
if(root != nullptr) {
st.push(root);
}
while(!st.empty()) {
TreeNode* node = st.top();
st.pop();
cout << node->val << " ";
if(node->right != nullptr) {
st.push(node->right);
}
if(node->left != nullptr) {
st.push(node->left);
}
}
}
// 非递归中序遍历
void inOrderTraversalIterative(TreeNode* root) {
stack<TreeNode*> st;
TreeNode* node = root;
while(node != nullptr || !st.empty()) {
while(node != nullptr) {
st.push(node);
node = node->left;
}
node = st.top();
st.pop();
cout << node->val << " ";
node = node->right;
}
}
// 非递归后序遍历
void postOrderTraversalIterative(TreeNode* root) {
stack<TreeNode*> st;
TreeNode* node = root;
TreeNode* lastVisited = nullptr;
while(node != nullptr || !st.empty()) {
while(node != nullptr) {
st.push(node);
node = node->left;
}
node = st.top();
if(node->right == nullptr || node->right == lastVisited) {
st.pop();
cout << node->val << " ";
lastVisited = node;
node = nullptr;
} else {
node = node->right;
}
}
}
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);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
// 递归遍历二叉树
cout << "递归前序遍历:";
preOrderTraversalRecursion(root);
cout << endl;
cout << "递归中序遍历:";
inOrderTraversalRecursion(root);
cout << endl;
cout << "递归后序遍历:";
postOrderTraversalRecursion(root);
cout << endl;
// 非递归遍历二叉树
cout << "非递归前序遍历:";
preOrderTraversalIterative(root);
cout << endl;
cout << "非递归中序遍历:";
inOrderTraversalIterative(root);
cout << endl;
cout << "非递归后序遍历:";
postOrderTraversalIterative(root);
cout << endl;
return 0;
}
```
上述代码实现了二叉树的递归和非递归前序、中序和后序遍历。其中,递归遍历使用了函数递归调用,非递归遍历则使用了栈结构来模拟递归过程。我们可以通过构造二叉树并调用上述遍历函数来测试代码的正确性。
阅读全文