c语言数组实现二叉树的问题,怎么把二叉树按顺序打印出来。

现在我用数组实现了二叉树,除了inorder,postorder,peroder,levelorder. 把二叉树按顺序打印(插入的顺序打印),请问可以实现吗,可以的请指教,不可以的话,能否告诉我另一种用数组顺序存储二叉树的方法,代码下面列出来了,可以直接复制调试。
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100
typedef struct node
{
int data;
struct node *left;
struct node *right;
}Node;
Node *newNode(int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = node->right = NULL;
return (node);
}

Node *insert(int arr[],Node *root, int i, int n)
{
if(i<n)
{
Node *temp = newNode(arr[i]);
root = temp;

root->left = insert(arr,root->left,2*i+1,n);

root->right = insert(arr, root->right,2*i+2,n);

}

return root;
}
int main()
{
int arr[] = {19,18,17,16,15,14,13,12,11,21,22,23,24,25,26,27,28,29,30};
int n = sizeof(arr)/sizeof(arr[0]);

Node *root = insert(arr,root,0,n);
}

第1个回答  2018-04-24
#include<stdio.h> #include<stdlib.h> struct BiTNode *stack[100]; struct BiTNode//定义结构体 { char data; struct BiTNode *lchild,*rchild; }; void later(struct BiTNode *&p) //前序创建树 { char ch; scanf("%c",&ch); if(ch==' ') p=NULL; else { p=(struct BiTNode *)malloc(sizeof(struct BiTNode)); p->data=ch; later(p->lchild); later(p->rchild); } } void print(struct BiTNode *p) //前序遍历(输出二叉树) { int i=-1; while(1) { while(p!=NULL) { stack[++i]=p->rchild;/*printf("ok?\n");*/ printf("%c",p->data); p=p->lchild; } if(i!=-1) { p=stack[i]; i--; } else return; } } void main()//主函数 { struct BiTNode *p,*t; later(p); print(p); }
第2个回答  2018-04-23
这是链式储蓄,没有数组储蓄一说,你把代码改形式试试。追问

没有数组存储吗?但作业就是用数组实现二叉树啊