#include <iostream>
#include <queue>
#include <stack>
#include <vector>
using namespace std;
int main() {
}
class Node {
public:
int val;
vector<Node*>children;
Node() {};
Node(int _val, vector<Node*>_children) {
val = _val;
children = _children;
}
};
//层序遍历
vector<vector<int>> Hierarchical_travel(Node* s) {
queue<Node*>que;
que.push(s);
vector<vector<int>>res;
while (!que.empty()) {
vector<int>vec;
int size = que.size();
while (size--) {
Node* s1 = que.front();
que.pop();
vec.push_back(s1->val);
for (auto a : s1->children) {
if (a != nullptr) {
que.push(a);
}
}
}
res.push_back(vec);
}
return res;
}
//前序遍历
vector<int> pretravel(Node* s) {
stack<Node*>sta;
vector<int>res;
if (s == NULL)return res;
sta.push(s);
while (!sta.empty()) {
Node* s1 = sta.top();
sta.pop();
res.push_back(s1->val);
for (int i = s1->children.size(); i >= 0; i--) {
if (s1->children[i] != nullptr) {
sta.push(s1->children[i]);
}
}
}
return res;
}
//后序遍历
vector<int> post_travel(Node* s) {
stack<Node*>sta;
vector<int>res;
if (s == NULL)return res;
sta.push(s);
while (!sta.empty()) {
Node* s1 = sta.top();
sta.pop();
res.push_back(s1->val);
for (auto a:s1->children) {
if (a != nullptr) {
sta.push(a);
}
}
}
return res;
}
多叉树的构造和其前序后序遍历
最新推荐文章于 2025-05-28 10:48:32 发布