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

這道題題目有點兒長,但題意不難,就是根據(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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容