hdoj3999 The order of a Tree

题目:

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:

  1. insert a key k to a empty tree, then the tree become a tree with
    only one node;
  2. 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

这道题题目有点儿长,但题意不难,就是根据输入的数建立一棵二叉搜索树,然后进行先序遍历。

#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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容