Build a file tree and print

The computer-based questions on the National Jiaotong University re-examination
give you a string of paths, such as: a\b\ca\d\eb\cst d\ You draw the directory structure contained in these paths, and the subdirectories are listed directly under the parent directory. The parent directory is indented one space to the right.
Build a tree recursively and print it recursively.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct node{
    
    
    string name;
    vector<node*> child;
};

void insertTree(node* &root, vector<string>& filepath, int layer, int n);
void printTree(node* &root);
void DFS(node* &root, int layer);

int main(){
    
    
    int n;
    cin>>n;
    node* root = new node;
    root->name = "root";
    while(n--){
    
    
        string path;
        cin>>path;
        vector<string> filepath;
        int s=0, e=0;
        while(e!=-1 && s<path.size()){
    
    
            e = path.find_first_of('\\', s);
            if(e!=-1) filepath.emplace_back(path.substr(s, e-s));
            else filepath.emplace_back(path.substr(s));
            s = e + 1;
        }
        insertTree(root, filepath, 0, filepath.size());
    }
    printTree(root);
    return 0;
}

void insertTree(node* &root, vector<string>& filepath, int layer, int n){
    
    
    if(layer>=n) return;
    bool exist = false;
    int i, child_num = root->child.size();
    for(i=0; i<child_num; i++){
    
    
        if(root->child[i]->name == filepath[layer]){
    
    
            exist = true;
            break;
        }
        else if(root->child[i]->name > filepath[layer]) break;
    }
    if(!exist){
    
    
        node* temp = new node;
        temp->name = filepath[layer];
        root->child.emplace(root->child.begin()+i, temp);
    }
    insertTree(root->child[i], filepath, layer+1, n);
    return;
}

void printTree(node* &root){
    
    
    int n = root->child.size();
    for(int i=0; i<n; i++) DFS(root->child[i], 0);
    return;
}

void DFS(node* &root, int layer){
    
    
    for(int i=0; i<layer; i++) cout<<' ';
    cout<<root->name<<endl;
    int n = root->child.size();
    for(int i=0; i<n; i++) DFS(root->child[i], layer+1);
    return;
}

Guess you like

Origin blog.csdn.net/sinat_37517996/article/details/105258363