一、先序遍历的实现及其性质
对于二叉树的先序遍历序列,序列的第一个一定是根结点。
void preorder(node* root)
{
if(root==NULL) return;
cout<<root->data;
preorder(root->lchild);
preorder(root->rchild);
}
二、中序遍历的实现及其性质
根结点总是位于左子树和右子树中间的位置,所以只要知道根结点,就可以通过根结点在中序遍历序列中的位置区分出左子树和右子树。
void inorder(node* root)
{
if(root==NULL) return;
inorder(root->lchild;
cout<<root->data;
inorder(root->rchild;
}
三、后序遍历的实现及其性质
后序序列的最后一个位置一定是根结点。
void postorder(node* root)
{
if(root==NULL) return;
postorder(root->lchild);
postorder(root->rchild);
cout<<root->data;
}
四、层序遍历
//记录层次的层序遍历代码
struct node{
int data;
int layer;
node* lchild;
node* rchild;
};
void layerorder(node* root)
{
queue<node*> q;
root->layer=1;
q.push(root);
while(!q.empty())
{
node* now=q.front();
q.pop();
cout<<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 NULL;
node* root=new node;
root->data=pre[prel];
int k;
for(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;
}