树的遍历

2020-08-18  本文已影响0人  1nvad3r
树的静态写法
#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

上一篇下一篇

猜你喜欢

热点阅读