多叉树的构造和其前序后序遍历

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值