1.创建二叉树节点建立顺序:首先添加根节点,然后添加左孩子,再添加左孩子的左孩子(递归原因导致以左或右为先,该案例先添加左孩子),以此类推,当不再添加左孩子时,然后添加右孩子.当右孩子不添加时,然后函数回调到父节点是否添加右孩子,以此类推,建立二叉树。
#include<iostream>
#include<string>
using namespace std;
struct Node{
int value;
Node *leftchild;
Node *rightchild;
};
Node *create(){
Node *node;
int data;
cin>>data;
if(data==0){
return NULL;
}
node=new Node;
node->value=data;
cout<<"输入"<<node->value<<"左孩子";
node->leftchild=create();
cout<<"输入"<<node->value<<"右孩子";
node->rightchild=create();
return node;
}
//前序遍历
void preshow(Node *n){
if(!n)
return ;
cout<<n->value<<endl;
preshow(n->leftchild);
preshow(n->rightchild);
}
//中续遍历
void inshow(Node *n){
if(!n)
return;
inshow(n->leftchild);
cout<<n->value;
inshow(n->rightchild);
}
//后序遍历
void lashow(Node *n){
lashow(n->leftchild);
lashow(n->rightchild);
cout<<n->value;
}
int main(){
Node *t=NULL;
cout<<"输入根节点 以数字0结束 "<<endl;
t=create();
cout<<"前序遍历"<<endl;
preshow(t);
cout<<"中序遍历"<<endl;
inshow(t);
cout<<"后序遍历"<<endl;
lashow(t);
}