#include<iostream>
#include<stdlib.h>
using namespace std;
// 定义二叉树节点结构体
typedef struct TB {
struct TB* lchild; // 左子树指针
struct TB* rchild; // 右子树指针
int data; // 节点数据
} BTnode, *BTree;
// 中序遍历二叉树的函数
void zhong(BTree T) {
BTree p = T, s[99];
int top = -1;
// 当树非空或栈非空时循环
while (p || top >= 0) {
// 沿左子树路径将节点入栈
while (p) {
s[++top] = p;
p = p->lchild;
}
// 弹出栈顶节点并访问
p = s[top--];
cout << p->data;
// 处理右子树
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;
// 调用中序遍历函数
zhong(T);
return 0;
}
C++实现二叉树中序遍历(非递归)示例
最新推荐文章于 2024-09-07 10:59:43 发布