美文网首页
树的遍历

树的遍历

作者: 1nvad3r | 来源:发表于2020-08-18 10:54 被阅读0次
    树的静态写法
    #include <vector>
    
    using namespace std;
    const int maxn = 31;
    
    struct Node {
        int data;
        vector<int> child;
    } nodes[maxn];
    
    树的遍历
    //先序遍历
    void preOrder(int root) {
        printf("%d ", nodes[root].data);
        for (int i = 0; i < nodes[root].child.size(); i++) {
            preOrder(nodes[root].child[i]);
        }
    }
    
    //层次遍历
    void levelOrder(int root) {
        queue<int> q;
        q.push(root);
        while (!q.empty()) {
            int now = q.front();
            printf("%d ", nodes[now].data);
            q.pop();
            for (int i = 0; i < nodes[now].child.size(); i++) {
                q.push(nodes[now].child[i]);
            }  
        }
    }
    

    1079 Total Sales of Supply Chain

    1090 Highest Price in Supply Chain

    1094 The Largest Generation

    1106 Lowest Price in Supply Chain

    1004 Counting Leaves

    1053 Path of Equal Weight

    相关文章

      网友评论

          本文标题:树的遍历

          本文链接:https://www.haomeiwen.com/subject/enqgdktx.html