二叉树前中后序遍历c++
时间: 2023-11-03 18:05:56 浏览: 92
以下是二叉树的前中后序遍历的 C++ 代码:
```c++
#include <iostream>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 前序遍历
void preorderTraversal(TreeNode* root) {
if (root == NULL) return;
cout << root->val << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// 中序遍历
void inorderTraversal(TreeNode* root) {
if (root == NULL) return;
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
// 后序遍历
void postorderTraversal(TreeNode* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->val << " ";
}
// 非递归前序遍历
void preorderTraversalNonRecursive(TreeNode* root) {
if (root == NULL) return;
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* curr = s.top();
s.pop();
cout << curr->val << " ";
if (curr->right != NULL) s.push(curr->right);
if (curr->left != NULL) s.push(curr->left);
}
}
// 非递归中序遍历
void inorderTraversalNonRecursive(TreeNode* root) {
if (root == NULL) return;
stack<TreeNode*> s;
TreeNode* curr = root;
while (curr != NULL || !s.empty()) {
while (curr != NULL) {
s.push(curr);
curr = curr->left;
}
curr = s.top();
s.pop();
cout << curr->val << " ";
curr = curr->right;
}
}
// 非递归后序遍历
void postorderTraversalNonRecursive(TreeNode* root) {
if (root == NULL) return;
stack<TreeNode*> s1, s2;
s1.push(root);
while (!s1.empty()) {
TreeNode* curr = s1.top();
s1.pop();
s2.push(curr);
if (curr->left != NULL) s1.push(curr->left);
if (curr->right != NULL) s1.push(curr->right);
}
while (!s2.empty()) {
cout << s2.top()->val << " ";
s2.pop();
}
}
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 << "Preorder traversal: ";
preorderTraversal(root);
cout << endl;
cout << "Inorder traversal: ";
inorderTraversal(root);
cout << endl;
cout << "Postorder traversal: ";
postorderTraversal(root);
cout << endl;
cout << "Non-recursive preorder traversal: ";
preorderTraversalNonRecursive(root);
cout << endl;
cout << "Non-recursive inorder traversal: ";
inorderTraversalNonRecursive(root);
cout << endl;
cout << "Non-recursive postorder traversal: ";
postorderTraversalNonRecursive(root);
cout << endl;
return 0;
}
```
输出结果为:
```
Preorder traversal: 1 2 4 5 3 6 7
Inorder traversal: 4 2 5 1 6 3 7
Postorder traversal: 4 5 2 6 7 3 1
Non-recursive preorder traversal: 1 2 4 5 3 6 7
Non-recursive inorder traversal: 4 2 5 1 6 3 7
Non-recursive postorder traversal: 4 5 2 6 7 3 1
```
阅读全文