总时间限制:
1000ms
内存限制:
128000kB
-
描述
-
依次给出n(0<n<=100000)<n<100000)< span="">个整数,请你以这n个数创建一棵二叉排序树,这棵排序树的根节点为第一个数,并输出其中序遍历和后序遍历。
输入
- 共两行,第一行为整数n,第二行为n个整数 输出
- 共两行,第一行为中序遍历,第二行为后序遍历 样例输入
-
8 23 45 12 6 7 89 13 47
样例输出
-
6 7 12 13 23 45 47 89 7 6 13 12 47 89 45 23
#include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <cstring> #include <cctype> #include <string> #include <iostream> #include <vector> #include <queue> #include <utility> #include <map> #include <set> #include <climits> using namespace std; typedef long long ll; typedef unsigned long long ull; const int maxn = 100000 + 5; struct TreeNode { int value; TreeNode* left_child; TreeNode* right_child; }; int num[maxn]; int n; void Push(int n, TreeNode* root) { if (n < root->value) { if (root->left_child == 0) { TreeNode* node = new TreeNode; // 注意需要用new运算符 node->value = n; node->left_child = 0; node->right_child = 0; root->left_child = node; //cout << "a" << endl; } else { //cout << "b" << endl; Push(n, root->left_child); } } else { if (root->right_child == 0) { TreeNode* node = new TreeNode; node->value = n; node->left_child = 0; node->right_child = 0; root->right_child = node; //cout << "c" << endl; } else { //cout << "d" << endl; Push(n, root->right_child); } } } void InOrder(vector<int> &result, TreeNode* root) { if (root == 0) return ; InOrder(result, root->left_child); result.push_back(root->value); InOrder(result, root->right_child); } void PostOrder(vector<int> &result, TreeNode* root) { if (root == 0) return ; PostOrder(result, root->left_child); PostOrder(result, root->right_child); result.push_back(root->value); } int main() { while(cin >> n) { TreeNode* root = new TreeNode; int temp; scanf("%d", &temp); root->value = temp; root->left_child = 0; root->right_child = 0; for (int i = 1; i < n; i++) { scanf("%d", &temp); //cout << temp << endl; Push(temp, root); } //cout << "build success" << endl; vector<int> in_order; vector<int> post_order; InOrder(in_order, root); PostOrder(post_order, root); for (int i = 0; i < in_order.size(); i++) { if (i != 0) cout << " "; cout << in_order[i]; } cout << endl; for (int i = 0; i < post_order.size(); i++) { if (i != 0) cout << " "; cout << post_order[i]; } cout << endl; } return 0; }