#include <stdio.h> #include <stdlib.h> #include <string.h> #define __MAX_LENGTH__ 20 typedef struct SqStack{//调用栈 int data[__MAX_LENGTH__]; int top; }SqStack; typedef struct SqBiTree{//顺序存储二叉树 elemType data[__MAX_LENGTH__]; int len; }SqBiTree; //按先序遍历一维数组作为存储结构的二叉树 int traTree(SqBiTree *t){ SqStack *stack = calloc(sizeof(SqStack),1); stack->top = 0;//将栈制空; int root; root = 0;//指向根节点; while((stack->top)>-1){//当栈不为空时,进入循环 while(root<__MAX_LENGTH__&&t->data[root]>=‘a‘){// printf("%c,",t->data[root]);//访问节点 stack->data[stack->top] = root;//节点入栈 stack->top ++; root = (root+1) * 2-1;//检查下一个左子树; } if(stack->top >-1){//栈非空访问,遍历右子树; stack->top --; root = (stack->data[stack->top]+1)*2; } } } int main(int argc, char *argv[]) { SqBiTree *p = calloc(sizeof(SqBiTree),1); strcpy(p->data,"abcdefghij"); traTree(p); return 0; }
时间: 2024-10-25 21:56:14