写了一些题发现自己二叉树还有点弱
先是建树 没什么特别 就是 边界条件注意一下
node *build(node *root,int left,int right){
root = new node();
int t = a[cnt++];
root -> index = t;
int i;
for(i = left;i < right;i++){
if(t == b[i])
break;
}
if(i > left && i < right){ /* 当中序排序中该元素不是 最左边 且满足是树 有左孩子*/
root -> left = build(root -> left,left,i);
/*** 一个根结点在中序排序 左边有元素时 有左孩子***/
}
if(i >= left && i < right -1){/* 同理 */
root -> right = build(root -> right,i+1,right);
/*** 一个根结点在中序排序中 右边有元素时 有右孩子***/
}
return root;
}
然后就是层次遍历 我用了个队列把每个节点的左右节点存在后面再pop出当前节点
void cengci(node *root){
queue<node *> p;
p.push(root); //加入根结点
while(!p.empty()){
cout<<p.front() -> index<<" ";
if(p.front() -> left != NULL){//左节点不空就加入
p.push(p.front()->left);
}
if(p.front() -> right != NULL){//同理
p.push(p.front() -> right);
}
p.pop();
}
}
完整的代码
#include<bits/stdc++.h>
using namespace std;
struct node{
int index;
node *left,*right;
node(){
left = NULL;
right = NULL;
}
};
int a[30];
int b[30];
int cnt = 0;
node *build(node *root,int left,int right){
root = new node();
int t = a[cnt++];
root -> index = t;
int i;
for(i = left;i < right;i++){
if(t == b[i])
break;
}
if(i > left && i < right){ /* 当中序排序中该元素不是 最左边 且满足是树 有左孩子*/
root -> left = build(root -> left,left,i);
/*** 一个根结点在中序排序 左边有元素时 有左孩子***/
}
if(i >= left && i < right -1){/* 同理 */
root -> right = build(root -> right,i+1,right);
/*** 一个根结点在中序排序中 右边有元素时 有右孩子***/
}
return root;
}
void cengci(node *root){
queue<node *> p;
p.push(root); //加入根结点
while(!p.empty()){
cout<<p.front() -> index<<" ";
if(p.front() -> left != NULL){//左节点不空就加入
p.push(p.front()->left);
}
if(p.front() -> right != NULL){//同理
p.push(p.front() -> right);
}
p.pop();
}
}
int main(){
node *root;
int n;
cin>>n;
for(int i = 0;i < n;i++){
cin>>a[i];
}
for(int i = 0;i < n;i++){
cin>>b[i];
}
root = build(root,0,n);
cengci(root);
return 0;
}