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

#include 
#include 
#include 
#include 
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;
}

你可能感兴趣的:(算法刷题,算法,数据结构)