二叉树的非递归遍历(前+中)

用栈实现

#include <stdio.h>
#include <stdlib.h>

typedef struct TREE {
	char data;
	struct TREE* Lchild;
	struct TREE* Rchild;
}TREE,*PTREE;

typedef struct STACK {
	struct TREE* data;
	struct STACK* next;
}STACK,*PSTACK;

PSTACK init() {
	PSTACK S = (PSTACK)malloc(sizeof(STACK));
	S->data = NULL;
	S->next = NULL;
	return S;
}

int isempty(PSTACK S) {
	if (S->next == NULL) {
		return 1;
	}
	else
	{
		return 0;
	}
}

void push(PSTACK S, PTREE T) {
	PSTACK NEWNODE = (PSTACK)malloc(sizeof(STACK));
	NEWNODE->data = T;
	NEWNODE->next = S->next;
	S->next = NEWNODE;
}

PSTACK pop(PSTACK S) {
	if (isempty(S)) {
		return;
	}
	PSTACK temp = S->next;
	S->next = temp->next;
	return temp;
}

void create(TREE** T) {
	char data;
	scanf("%c", &data);
	getchar();
	if (data != '#') {
		*T = (PTREE)malloc(sizeof(TREE));
		(*T)->data = data;
		create(&(*T)->Lchild);
		create(&(*T)->Rchild);
	}
	else
	{
		*T = NULL;
	}
}

void preorder(PSTACK S,PTREE T) {
	PTREE node = T;
	while (node || !isempty(S)) {
		if (node) {
			printf("%c", node->data);
			push(S, node);
			node = node->Lchild;
		}
		else
		{
			node = pop(S)->data;
			node = node->Rchild;
		}
	}
}

void inorder(PSTACK S, PTREE T) {
	PTREE node = T;
	while (node || !isempty(S)) {
		if (node) {
			push(S, node);
			node = node->Lchild;
		}
		else
		{
			node = pop(S)->data;
			printf("%c", node->data);
			node = node->Rchild;
		}
	}
}

int main() {
	PTREE T;
	create(&T);
	PSTACK S = init();
	preorder(S, T);
	printf("\n");
	inorder(S, T);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值