solution.cpp 1.5 KB
Newer Older
CSDN问答's avatar
CSDN问答 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#include <iostream>
#include <unordered_map>

using namespace std;

//定义结构体表示一个节点
struct Node {
    string name;
    Node* left;
    Node* right;
};

//建立二叉树的函数
Node* build_tree(int n) {
    // 建立根节点
    string line;
    getline(cin, line);
    stringstream ss(line);
    string name, is, the, father, s;
    ss >> name >> is >> the >> father >> s;
    Node* root = new Node{name, nullptr, nullptr};

    // 建立剩余的节点
    for (int i = 1; i < n; i++) {
        getline(cin, line);
        stringstream ss(line);
        string name, is, the, father, s;
        ss >> name >> is >> the >> father >> s;
        Node* cur = root;
        while (true) {
            if (father == cur->name && s == "son") {
                if (cur->left == nullptr) {
                    cur->left = new Node{name, nullptr, nullptr};
                    break;
                } else if (cur->right == nullptr) {
                    cur->right = new Node{name, nullptr, nullptr};
                    break;
                } else {
                    cur = cur->left;
                }
            } else {
                cur = cur->right;
            }
        }
    }
    return root;
}

//输出前序遍历的函数
void preorder(Node* root) {
    cout << root->name << " ";
    if (root->left != nullptr) preorder(root->left);
    if (root->right != nullptr) preorder(root->right);
}

int main() {
    int n;
    cin >> n;
    cin.ignore();
    Node* root = build_tree(n);
    preorder(root);
    return 0;
}