c++编写二叉树前序遍历非递归
时间: 2023-08-06 21:07:48 浏览: 122
C语言实现二叉树的前序遍历(非递归)
下面是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;
}
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()) {
TreeNode* node = stk.top();
stk.pop();
cout<<node->val<<" ";
if(node->right != NULL) {
stk.push(node->right);
}
if(node->left != NULL) {
stk.push(node->left);
}
}
}
int main() {
// test case
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<<"preorderTraversal:"<<endl;
preorderTraversal(root);
return 0;
}
```
上面的代码通过使用栈来模拟递归过程,实现了二叉树的前序遍历。
阅读全文