天天看點

已知二叉樹的中序周遊和後序周遊,如何求前序周遊

     在已知二叉樹的前序周遊和中序周遊的情況下,求出了後序周遊。

那麼,對稱地,如果已知二叉樹的後序周遊和中序周遊,如何求前序周遊呢?

其實思路與​​上文​​完全類似。

代碼如下:

1. // InPost2Pre.cpp : Defines the entry point for the console application.
2. //
3.   
4. #include "stdafx.h"
5. #include <iostream>
6. using namespace
7.   
8. struct
9. {  
10. struct
11. struct
12. char
13. };  
14.   
15. TreeNode* BinaryTreeFromOrderings(char* inorder,char* postorder, int
16. {  
17. if(length == 0)   
18.     {  
19. return
20.     }  
21. //We have root then;
22. new TreeNode;//Noice that [new] should be written out.
23.   node->elem = *(postorder+length-1);  
24.   cout<<node->elem<<endl;  
25. int
26. for(;rootIndex <length; rootIndex++) 
27.     {  
28. if(inorder[rootIndex] == *(postorder+length-1)) 
29. break;  
30.     }  
31. //在循環條件而非循環體完成了對變量值的改變。
32. //Left
33.   node->left = BinaryTreeFromOrderings(inorder, postorder, rootIndex); 
34. //Right
35.   node->right = BinaryTreeFromOrderings(inorder + rootIndex + 1, postorder + rootIndex, length - (rootIndex+1)); 
36. //node->right = *(postorder+length-2);
37.   
38. return
39. }  
40.   
41.   
42. int main(int argc,char* argv[])  
43. {  
44. "Hello World!\n");   
45. char* in="ADEFGHMZ"; 
46. char* po="AEFDHZMG";     
47.         BinaryTreeFromOrderings(in, po, 8);  
48. "\n");  
49. return
50. }      
// InPost2Pre.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

struct TreeNode
{
  struct TreeNode* left;
  struct TreeNode* right;
  char  elem;
};

TreeNode* BinaryTreeFromOrderings(char* inorder, char* postorder, int length)
{
  if(length == 0)
    {
      return NULL;
    }
  //We have root then;
  TreeNode* node = new TreeNode;//Noice that [new] should be written out.
  node->elem = *(postorder+length-1);
  cout<<node->elem<<endl;
  int rootIndex = 0;
  for(;rootIndex <length; rootIndex++)
    {
      if(inorder[rootIndex] == *(postorder+length-1))
      break;
    }
  //在循環條件而非循環體完成了對變量值的改變。
  //Left
  node->left = BinaryTreeFromOrderings(inorder, postorder, rootIndex);
  //Right
  node->right = BinaryTreeFromOrderings(inorder + rootIndex + 1, postorder + rootIndex, length - (rootIndex+1));
  //node->right = *(postorder+length-2);

  return node;
}


int main(int argc, char* argv[])
{
  printf("Hello World!\n");
  char* in="ADEFGHMZ";
  char* po="AEFDHZMG";  
        BinaryTreeFromOrderings(in, po, 8);
        printf("\n");
  return 0;
}