1基础
1 .1 二叉树的链表结构
struct node{
typename data;
node* lchild;
node* ychild;
};
建立树前根节点不存在 因此初始化为
node* root=NULL;
1.2建立新结点
node* newNode(int v){//v为权值
node* Node=new node;
Node->data=v;
Node->lchild=Node->rchild=NULL;
return Node;
}
1.3 查找 修改
void search(node* root,int x,int newdata){
if(root==NULL){
return;
}
if(root->data==x)
root->data=newdata;
search(node->lchild, x, newdata);
search(node->rchild, x, newdata);
}
1.4 插入
void insert(node* &root,int x){
if(root==NULL){
root=newNode(x);
return;
}
if(){
insert(root->lchild,x);
}
else{
insert(root->rchild,x);
}
}
NOTE 在插入时 root前有&,原因为:新建结点/对二叉树做出修改则需要&,而如果只是修改当前结点的内容/遍历树时则不需要&
在新建结点时,一定要让左右指针域为NULL!!
1.5 二叉树的创建
node* Creat(int data[],int n){
node* root=NULL;
for(int i=0;i<n;i++){
insert(root,data[i]);
}
return root;
}
2 遍历–
ps:无论先序遍历还是后序遍历都需要知道中序遍历才能唯一的确定一棵树!
2.1先序遍历
void preorder(node *root){
if(root==NULL){
return;//到达空树 递归的边界
}
//根结点数据
printf("%d\n",root->data);
preorder(root->lchild);
preorder(root->rchild);
}
2.2 中序遍历
2.3 后序遍历
void postorder(node* root){
if(root==NULL){
return;
}
postorder(root->lchild);
postorder(root->rchild);
printf("%d\n",root->data);
}
2.4 层次遍历
void Layorder(node* root){
queue<node*> q; //队列中存的是地址
root->layer=1;
q.push(root);//根结点入队
while(!q.empty()){
node* now=q.front();
q.pop();
printf("%d",now-<data);
if(now->lchild!=NULL){
now->lchild->layer=now->layer+1;
q.push(now->lchild);
}
if(now->rchild!=NULL){
now->rchild->layer=now->layer+1;
q.push(now->rchild);
}
}
}
重要问题:知先序遍历和中序遍历重建二叉树
node* Create(int preL,int preR,int inL,int inR){
if(preL>preR)
return;
node* root=new node;
root->data=pre[preL];
int k;
for(int k=inL;k<=inR;k++){
if(in[k]==pre[preL]){
break;
}
int numLeft=k-inL;
root->lchild=Create(preL+1, preL+numLeft, inL,k-1);
root->rchild=Create(preL+numLeft+1, preR, k+1,inR);
return root;
}
}