#include<iostream>
#include<stdlib.h>
using namespace std;
// 定义二叉树节点结构体
typedef struct TB {
struct TB* lchild; // 左子树指针
struct TB* rchild; // 右子树指针
int data; // 节点数据
} BTnode, *BTree;
// 先序遍历二叉树的函数
void qian(BTree T) {
BTree s[99], p = T;
int top = -1;
// 当树非空或栈非空时循环
while (p || top >= 0) {
// 沿左子树路径将节点入栈并输出节点数据
while (p) {
s[++top] = p;
cout << p->data;
p = p->lchild;
}
// 弹出栈顶节点,处理右子树
p = s[top--];
p = p->rchild;
}
}
int main() {
// 动态分配内存创建二叉树
BTree T = (BTree)malloc(sizeof(BTnode)), t1, t2, t3, t4, t5;
T->data = 0;
T->lchild = (BTree)malloc(sizeof(BTnode));
T->rchild = (BTree)malloc(sizeof(BTnode));
t1 = T->lchild;
t2 = T->rchild;
t1->data = 1;
t2->data = 2;
t1->lchild = NULL;
t1->rchild = NULL;
t2->lchild = (BTree)malloc(sizeof(BTnode));
t2->rchild = (BTree)malloc(sizeof(BTnode));
t3 = t2->lchild;
t4 = t2->rchild;
t3->data = 3;
t4->data = 4;
t3->lchild = NULL;
t3->rchild = NULL;
t4->lchild = NULL;
t4->rchild = NULL;
// 调用先序遍历函数
qian(T);
return 0;
}
在main()函数中。创建的二叉树:
运行结果: