題目:
Problem Description
As we know,the shape of a binary search tree is greatly related to the order of keys we insert. To be precisely:
- insert a key k to a empty tree, then the tree become a tree with
only one node; - insert a key k to a nonempty tree, if k is less than the root ,insert
it to the left sub-tree;else insert k to the right sub-tree.
We call the order of keys we insert “the order of a tree”,your task is,given a oder of a tree, find the order of a tree with the least lexicographic order that generate the same tree.Two trees are the same if and only if they have the same shape.
Input
There are multiple test cases in an input file. The first line of each testcase is an integer n(n <= 100,000),represent the number of nodes.The second line has n intergers,k1 to kn,represent the order of a tree.To make if more simple, k1 to kn is a sequence of 1 to n.
Output
One line with n intergers, which are the order of a tree that generate the same tree with the least lexicographic.
Sample Input
4
1 3 4 2
Sample Output
1 3 2 4
這道題題目有點兒長,但題意不難,就是根據(jù)輸入的數(shù)建立一棵二叉搜索樹,然后進行先序遍歷。
#include <iostream>
#include <cstring>
using namespace std;
int n;
int cnt;
struct Node {
int val;
Node *lch;
Node *rch;
};
Node* insertNode(Node *p, int num) {
if (p == NULL) {
Node *q = new Node();
q->val = num;
q->lch = q->rch = NULL;
return q;
}
else {
if (num < p->val) p->lch = insertNode(p->lch, num);
else p->rch = insertNode(p->rch, num);
return p;
}
}
void preVisit(Node *p) {
if (p) {
if (cnt > 0) cout << " ";
cout << p->val;
++cnt;
preVisit(p->lch);
preVisit(p->rch);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
while (cin >> n) {
cnt = 0;
int num;
Node *root = NULL;
for (int i = 0;i < n;++i) {
cin >> num;
root = insertNode(root, num);
}
preVisit(root);
cout << endl;
}
return 0;
}