#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
void preorder(char tree[], int i)
{
if(tree[i] != '\0')
{
printf("%c", tree[i]);
preorder(tree, i*2);
preorder(tree, i*2+1);
}
}
void inorder(char tree[], int i)
{
if(tree[i] != '\0')
{
inorder(tree, i*2);
printf("%c", tree[i]);
inorder(tree, i*2+1);
}
}
void postorder(char tree[], int i)
{
if(tree[i] != '\0')
{
postorder(tree, i*2);
postorder(tree, i*2+1);
printf("%c", tree[i]);
}
}
void main()
{
char ArrayTree[36] = { 0,'A','B','C','D','E','F','G','H','I','J','K',0, };
printf("\n preorder : ");
preorder(ArrayTree, 1);
printf("\n inorder: ");
inorder(ArrayTree, 1);
printf("\n postorder: ");
postorder(ArrayTree, 1);
getchar();
}
Current Print result
preorder: ABDHIEJKCFG / inorder: HDIBJEKAFCG / postorder: HIDJKEBFGCA /
But I want to print like this
preoder: ABDHEIJCFGK / inorder: HDBIEJAFCGK / postorder: HDIJEBFKGCA /
How to change it?
The code looks correct but your data is wrong. It doesn't represent the tree in your diagram. For example, the right sibling of 'H'
should be 0 (or NULL).
A corrected array looks like:
char ArrayTree[32] = { 0,'A','B','C','D','E','F','G','H',0,'I','J',0,0,0,'K' };
The size only needs to be 32 to contain a complete tree of height 5 (plus the unused 0 index).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.