#include
using namespace std;
typedef node *tree;
struct node {
int data;
tree l,r;
};
tree create(){
tree hd=(tree)malloc(sizeof(tree));
hd->l=NULL;
hd->r=NULL;
return hd;
}
相关题目
int a[31],b[31];\\存放遍历顺序的数组,a为先序
tree build_fst_mid(int rt,int bg,int ed){
tree head=create();
head->data=a[rt];
int i;
for(i=bg;i<=ed;i++){
if(a[rt]==b[i]){
if (i != bg)
head->l = build_fst_mid(rt + 1, bg, i - 1);
if (i != ed)
head->r = build_fst_mid(rt +i-bg+1, i + 1, ed);
}
}
return head;
}
引用:
tree head=build_fst_mid(0,0,n-1);
相关题目
int a[31],b[31];//存放遍历顺序的数组,a为后序
tree build_lst_mid(int rt,int bg,int ed){
tree head=create();
head->data=a[rt];
int i;
for(i=bg;i<=ed;i++){
if(a[rt]==b[i]){
if(i!=bg)
head->l=build_lst_mid(rt-(ed-i)-1,bg,i-1);
if(i!=ed)
head->r=build_lst_mid(rt-1,i+1,ed);
}
}
return head;
}
引用:
tree head=build_lst_mid(n-1,0,n-1);
void invertTree(tree root) {//反转
if(root == NULL)
return ;
tree p = root;
p = root->l;
root->l= root->r;
root->r = p;
invertTree(root->l);
invertTree(root->r);
}
queue <tree> q1,q2;
int flag=1;
q1.push(head);
while(n){//n为结点总数
if(flag){
while(!q1.empty()){
tree node=q1.front();
if(node->l!=NULL) q2.push(node->l);
if(node->r!=NULL) q2.push(node->r);
if(n==1)
printf("%d",node->data);
else
printf("%d ",node->data);
q1.pop();
n--;
}
flag=0;
}
else{
while(!q2.empty()){
tree node=q2.front();
if(node->l!=NULL) q1.push(node->l);
if(node->r!=NULL) q1.push(node->r);
if(n==1)
printf("%d",node->data);
else
printf("%d ",node->data);
q2.pop();
n--;
}
flag=1;
}
}
pre_order(tree root){
if(root==NULL)
return
cout <<root.data <<endl;
pre_order(root.l);
pre_order(root.r);
}
mid_order(tree root){
if(root==NULL)
return
pre_order(root.l);
cout <<root.data <<endl;
pre_order(root.r);
}
lst_order(tree root){
if(root==NULL)
return
pre_order(root.l);
pre_order(root.r);
cout <<root.data <<endl;
}
相关题目
一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点,
void insert(tree root,int data){
if(root==NULL){
root=create();
root->data=data;
return ;
}
else{
if(data>=root->data)
insert(root->r,data);
else{
insert(root->l,data);
}
}
}
未完待续