数组存储二叉树(下标从1开始)。i>时父节点为i/2;当i2<=节点个数时,左子树为i2;当i2+1<=节点个数时,右子数为2i+1
void PreTra(int i){
if(i >= len)
return ;
printf("%c",a[i]);
PreTra(i*2);
PreTra(i*2+1);
return ;
}
void InTra(int i){
if(i >= len)
return ;
InTra(i*2);
printf("%c",a[i]);
InTra(i*2+1);
return ;
}
void LaTra(int i){
if(i >= len)
return ;
LaTra(i*2);
LaTra(i*2+1);
printf("%c",a[i]);
return ;
}
int main(){
int i;
char ch;
len = 1;
while(ch = getchar()){
a[len++] = ch;
if(ch == '
')
break;
}
len --;
PreTra(1);
printf("
");
InTra(1);
printf("
");
LaTra(1);
return 0;
}
先序递归创建二叉树(链表)
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
struct node{
char data;
node * left;
node * right;
};
void CreateTree(node ** p){
char ch = getchar();
if(ch == ' '){
*p = NULL;
return ;
}
(*p) = (node*) malloc(sizeof(node));
(*p)->data = ch;
CreateTree(&((*p)->left));
CreateTree(&((*p)->right));
}
void PreTra(node *p){
if(!p)
return ;
printf("%c",p->data);
PreTra(p->left);
PreTra(p->right);
}
int main(){
char ch;
node * tree;
CreateTree(&tree);
PreTra(tree);
// printf("Tree
");
return 0;
}