C++非递归前序遍历二叉树并打印
时间: 2024-06-19 16:04:07 浏览: 105
C++非递归前序遍历二叉树的代码如下:
```cpp
#include <iostream>
#include <stack>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void preorderTraversal(TreeNode* root) {
if (!root) {
return;
}
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* node = s.top();
s.pop();
cout << node->val << " ";
if (node->right) {
s.push(node->right);
}
if (node->left) {
s.push(node->left);
}
}
}
int main() {
// Create a binary tree
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);
// Non-recursive preorder traversal
cout << "Non-recursive preorder traversal: ";
preorderTraversal(root);
cout << endl;
return 0;
}
```
非递归前序遍历二叉树的思路是使用栈来模拟递归过程。我们首先把根节点入栈,然后在循环中不断取出栈顶元素,输出它的值,并依次把其右子节点和左子节点入栈。由于栈是后进先出的数据结构,所以先入栈右子节点再入栈左子节点可以保证左子节点先被访问。
阅读全文