二叉排序树非递归遍历代码c++
时间: 2023-12-10 20:34:54 浏览: 80
二叉排序树模板类c++
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(NULL), right(NULL) {}
};
// 先序遍历
void preOrder(TreeNode* root) {
if (root == NULL) {
return;
}
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* node = s.top();
s.pop();
cout << node->val << " ";
if (node->right != NULL) {
s.push(node->right);
}
if (node->left != NULL) {
s.push(node->left);
}
}
}
// 中序遍历
void inOrder(TreeNode* root) {
if (root == NULL) {
return;
}
stack<TreeNode*> s;
TreeNode* node = root;
while (node != NULL || !s.empty()) {
while (node != NULL) {
s.push(node);
node = node->left;
}
node = s.top();
s.pop();
cout << node->val << " ";
node = node->right;
}
}
// 后序遍历
void postOrder(TreeNode* root) {
if (root == NULL) {
return;
}
stack<TreeNode*> s1, s2;
s1.push(root);
while (!s1.empty()) {
TreeNode* node = s1.top();
s1.pop();
s2.push(node);
if (node->left != NULL) {
s1.push(node->left);
}
if (node->right != NULL) {
s1.push(node->right);
}
}
while (!s2.empty()) {
cout << s2.top()->val << " ";
s2.pop();
}
}
int main() {
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(3);
root->right = new TreeNode(7);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(4);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(8);
cout << "Preorder traversal: ";
preOrder(root);
cout << endl;
cout << "Inorder traversal: ";
inOrder(root);
cout << endl;
cout << "Postorder traversal: ";
postOrder(root);
cout << endl;
return 0;
}
```
阅读全文