poj: 2255

跟LEETCODE的preorder,inorder转postorder题很像

 1 #include <iostream>

 2 #include <stdio.h>

 3 #include <string>

 4 #include <stack>

 5 #include <map>

 6 #include <vector>

 7 #include <algorithm>

 8 using namespace std;

 9 

10 struct node {

11     char val;

12     node *left, *right;

13     node(char v) : val(v), left(NULL), right(NULL) { }

14 };

15 

16 node* preIn(string preorder, string inorder, int prebeg, int inbeg, int len) {

17     if (!len) return NULL;

18     node *tmp = new node(preorder[prebeg]);

19     int leftlen, rightlen;

20     for (int i = inbeg; i < inbeg+len; ++i) {

21         if (tmp->val == inorder[i]) {

22             leftlen = i - inbeg;

23             rightlen = len - leftlen - 1;

24             break;

25         }

26     }

27     tmp->left = preIn(preorder, inorder, prebeg+1, inbeg, leftlen);

28     tmp->right = preIn(preorder, inorder, prebeg+leftlen+1, inbeg+leftlen+1, rightlen);

29     return tmp;

30 }

31 

32 string postString(node *root) {

33     if (!root) return "";

34     return postString(root->left) + postString(root->right) + root->val;

35 }

36 

37 int main()

38 {

39     string preorder, inorder;

40     while (cin >> preorder && cin >> inorder) {

41         node *root = preIn(preorder, inorder, 0, 0, preorder.size());

42         string postorder = postString(root);

43         cout << postorder << endl;

44     }

45 

46     return 0;

47 }

 

你可能感兴趣的:(poj)