#include <iostream>
#include <stack>
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int val) : data(val), left(nullptr), right(nullptr) {}
};
void iterativePreorder(TreeNode* root) {
if (root == nullptr) {
return;
}
std::stack<TreeNode*> nodeStack;
nodeStack.push(root);
while (!nodeStack.empty()) {
TreeNode* node = nodeStack.top();
nodeStack.pop();
std::cout << node->data << " ";
if (node->right != nullptr) {
nodeStack.push(node->right);
}
if (node->left != nullptr) {
nodeStack.push(node->left);
}
}
}
void iterativeInorder(TreeNode* root) {
if (root == nullptr) {
return;
}
std::stack<TreeNode*> nodeStack;
TreeNode* current = root;
while (current != nullptr || !nodeStack.empty()) {
while (current != nullptr) {
nodeStack.push(current);
current = current->left;
}
current = nodeStack.top();
nodeStack.pop();
std::cout << current->data << " ";
current = current->right;
}
}
void iterativePostorder(TreeNode* root) {
if (root == nullptr) {
return;
}
std::stack<TreeNode*> nodeStack1, nodeStack2;
nodeStack1.push(root);
while (!nodeStack1.empty()) {
TreeNode* node = nodeStack1.top();
nodeStack1.pop();
nodeStack2.push(node);
if (node->left != nullptr) {
nodeStack1.push(node->left);
}
if (node->right != nullptr) {
nodeStack1.push(node->right);
}
}
while (!nodeStack2.empty()) {
TreeNode* node = nodeStack2.top();
nodeStack2.pop();
std::cout << node->data << " ";
}
}
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);
std::cout << "Iterative Preorder Traversal:" << std::endl;
iterativePreorder(root);
std::cout << std::endl;
std::cout << "Iterative Inorder Traversal:" << std::endl;
iterativeInorder(root);
std::cout << std::endl;
std::cout << "Iterative Postorder Traversal:" << std::endl;
iterativePostorder(root);
std::cout << std::endl;
return 0;
}
我们定义了iterativePreorder
、iterativeInorder
和iterativePostorder
函数来实现二叉树的非递归前序、中序和后序遍历。在main
函数中,我们构建了一个简单的二叉树,并分别调用这三个函数来进行遍历。