给我用c++编写一个二叉树先序非递归遍历实例
时间: 2024-05-09 16:18:00 浏览: 68
c++实现二叉树的4种遍历(递归和非递归)(csdn)————程序.pdf
可以参考以下代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 50
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
typedef struct Stack {
TreeNode* data[MAX_SIZE];
int top;
} Stack;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
void push(Stack* s, TreeNode* node) {
if (s->top == MAX_SIZE-1) {
printf("Stack overflow.\n");
return;
}
s->data[++s->top] = node;
}
TreeNode* pop(Stack* s) {
if (s->top == -1) {
return NULL;
}
return s->data[s->top--];
}
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
Stack s;
s.top = -1;
push(&s, root);
while (s.top != -1) {
TreeNode* node = pop(&s);
printf("%d ", node->val);
if (node->right != NULL) {
push(&s, node->right);
}
if (node->left != NULL) {
push(&s, node->left);
}
}
}
int main() {
TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
printf("Preorder traversal of the binary tree: ");
preorderTraversal(root);
printf("\n");
return 0;
}
```
输出结果为:
```
Preorder traversal of the binary tree: 1 2 4 5 3 6 7
```
请问还有什么我可以帮您解答的吗?
阅读全文