先跟遍历和中跟遍历建树

来源:互联网 发布:c 二维数组赋值结构 编辑:程序博客网 时间:2024/05/01 13:27
#include <iostream>
using namespace std;


class Node{
public:
int value;
Node* left;
Node* right;
Node(int t):value(t),left(NULL),right(NULL){}
Node():value(0),left(NULL),right(NULL){}
};
void CreateTree(Node *root, int bstart, int bend,int mstart, int mend, int *before, int *mid, int len)
{
         if (root == NULL)
                   return;
 
         if ( bstart > bend )
                   return;
 
         if ( mstart > mend )
                   return;
 
         //前序遍历的第一个值为根节点的值
         root->value = before[bstart];
         //在中序遍历中找出该值所在的位置
         int temp;                    //记下该值的位置
         int count =0;              //记下该左子树中有多少个节点
         for ( int i=mstart; i<= mend; i++)
         {
                   if ( mid[i] == root->value )
                   {
                            temp = i;
                            break;
                  }
                   count++;
         }
 
         //进行递归,建立左子树和右子树,注意子树为空的情况
         if ( count == 0 )
                   root->left = NULL;
         else
         {
                   Node *left = new Node;
                   root->left = left;
                   CreateTree(left, bstart+1, bstart+count, mstart, temp-1, before, mid, len);
         }
 
         if ( temp == mend)
                   root->right = NULL;
         else          
         {
                   Node *right = new Node;
                   root->right = right;
                   CreateTree(right, bstart+count+1,bend,temp+1,mend,before, mid, len);
         }
}
void Later(Node *root)
{
if(root!=NULL)
{
Later(root->left);
Later(root->right);
cout<<root->value<<" ";
}
}
int main()
{
int n,a[1000],b[1000];
while(cin>>n)
{
for(int i=0;i<n;i++)
cin>>a[i];
for(int j=0;j<n;j++)
cin>>b[j];
Node *root=NULL;
root=new Node();
CreateTree(root,0,n-1,0,n-1,a,b,n);
Later(root);


}
return 0;
}
原创粉丝点击