PAT 1020. Tree Traversals (25)
1020. Tree Traversals (25)
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:7 2 3 1 5 7 6 4 1 2 3 4 5 6 7Sample Output:
4 1 6 3 5 7 2
1 #include <iostream> 2 #include <queue> 3 4 using namespace std; 5 6 struct Node 7 { 8 int val; 9 Node* left; 10 Node* right; 11 Node(){ val = 0; left = right = nullptr; } 12 }; 13 14 static int postOrder[30]; 15 static int inOrder[30]; 16 17 int InOrderFindIndex(int val, int inLeft, int inRight) 18 { 19 for (int i = inLeft; i < inRight; i++) 20 if (inOrder[i] == val) 21 return i; 22 } 23 24 Node* ConstructTree(int postLeft, int postRight, int inLeft, int inRight) 25 { 26 if (postLeft == postRight) 27 return nullptr; 28 29 Node* root = new Node; 30 root->val = postOrder[postRight-1]; 31 int index = InOrderFindIndex(root->val, inLeft, inRight); 32 int leftLength = index - inLeft; 33 int rightLength = inRight - index - 1; 34 root->left = ConstructTree(postLeft, postLeft + leftLength, inLeft, index); 35 root->right = ConstructTree(postLeft + leftLength, postRight - 1, index + 1, inRight); 36 37 return root; 38 } 39 40 void LevelOrderTraversal(Node* root, int NodeNum) 41 { 42 queue<Node*> que; 43 que.push(root); 44 int cnt = 0; 45 while (!que.empty()) 46 { 47 Node* last = que.front(); 48 que.pop(); 49 cout << last->val; 50 ++cnt; 51 if (cnt < NodeNum) 52 cout << " "; 53 if (last->left) 54 que.push(last->left); 55 if (last->right) 56 que.push(last->right); 57 } 58 59 60 } 61 62 int main() 63 { 64 int NodeNum; 65 cin >> NodeNum; 66 67 for (int i = 0; i < NodeNum; i++) 68 cin >> postOrder[i]; 69 for (int i = 0; i < NodeNum; i++) 70 cin >> inOrder[i]; 71 72 Node* root; 73 74 root = ConstructTree(0, NodeNum, 0, NodeNum); 75 LevelOrderTraversal(root, NodeNum); 76 }