已知先序遍历和中序遍历求后序遍历——二叉树

来源:互联网 发布:软件测试有前途吗天涯 编辑:程序博客网 时间:2024/06/06 02:07

思想数据结构课都讲过,就是从pre下手,因为处理pre是连续的一段段,头上的都是根节点,所以接口函数为:

void solve(tree* root,int low,int high,int rootpos)

root为当前节点,low,high都是相对于mid串而言的;rootpos为根节点在pre串中的位置

思路递归,代码如下:

[cpp] view plaincopy
  1. #include "iostream"  
  2. #include "string"  
  3. using namespace std;  
  4.   
  5. struct tree  
  6. {  
  7.     char name;  
  8.     tree* left;  
  9.     tree* right;  
  10. };  
  11. string pre,mid;  
  12.   
  13. //tree* solve(tree* root,int low,int high,int rootpos)  
  14. //{  
  15. //  if (low>high)  
  16. //      return NULL;  
  17. //  if(low==high)  
  18. //  {  
  19. //      tree *temp=(tree*) malloc(sizeof(tree*));  
  20. //      temp->left=temp->right=NULL;  
  21. //      temp->name=mid[low];  
  22. //      return temp;  
  23. //  }  
  24. //  int rpos=-1;  
  25. //  while (mid[++rpos]!=pre[rootpos]);  
  26. //  root->name=pre[rootpos];  
  27. //  root->left=(tree*) malloc(sizeof(tree*));  
  28. //  root->right=(tree*) malloc(sizeof(tree*));  
  29. //  root->left=solve(root->left,low,rpos-1,rootpos+1);  
  30. //  root->right=solve(root->right,rpos+1,high,rpos+1);  
  31. //  return root;  
  32. //}  
  33.   
  34. void solve(tree* root,int low,int high,int rootpos)  
  35. {  
  36.     if(low==high)  
  37.     {  
  38.         root->left=root->right=NULL;  
  39.         root->name=mid[low];  
  40.         return;  
  41.     }  
  42.     int rpos=-1;  
  43.     while (mid[++rpos]!=pre[rootpos]);  
  44.     root->name=pre[rootpos];  
  45.     root->left=root->right=NULL;  
  46.     if (low<=rpos-1)  
  47.     {  
  48.         root->left=(tree*) malloc(sizeof(tree*));  
  49.         solve(root->left,low,rpos-1,rootpos+1);  
  50.     }  
  51.     if(rpos+1<=high)  
  52.     {  
  53.         root->right=(tree*) malloc(sizeof(tree*));  
  54.         solve(root->right,rpos+1,high,rpos+1);  
  55.     }  
  56. }  
  57.   
  58. void TraversalPost(tree* node)  
  59. {  
  60.     if (node)  
  61.     {  
  62.         TraversalPost(node->left);  
  63.         TraversalPost(node->right);  
  64.         printf("%c ",node->name);  
  65.     }  
  66. }  
  67.   
  68. void main()  
  69. {  
  70.     int i,j;  
  71.     tree* root=(tree*)malloc(sizeof(tree*));  
  72.     while (cin>>pre>>mid)  
  73.     {  
  74.         root->left=root->right=NULL;  
  75.         root->name=mid[0];  
  76.         solve(root,0,mid.length()-1,0);  
  77.         TraversalPost(root);  
  78.         cout<<endl;  
  79.     }  
  80. }  

其中被注释掉的那部分也能用的,和下面同名函数是同种方法,两种形式。

调用就是root=solve(root,0,mid,length()-1,0);

=======================================================================

Hope you enjoy it !

0 0
原创粉丝点击