一、N叉树的节点 Node 定义如下:
class Node
{
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
二、根据层序遍历的结果数组,构造 N叉树:
#include <iostream>
#include<vector>
using std::cout;
using std::endl;
using std::string;
using std::vector;
class Node
{
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
class Solution {
public:
vector<int> preorder(Node* root) {
if (root == NULL) return {};
cout << "enter:" << root->val << endl;
childarr.push_back(root->val);
for (Node* child : root->children)
{
preorder(child);
}
cout << "Leave:" << root->val << endl;
return childarr;
}
private:
vector<int> childarr;
};
// 1
// / | \
// 3 2 4
// / \
// 5 6
int main()
{
//给出N叉树的层序遍历 数组
vector<int> root = { 1, NULL, 3, 2, 4, NULL, 5, 6 };
//根据层序遍历的结果 ,构造出多叉树
Node Tree[6];
for (int i=0,j=0;i<6 && j<8 ;i++,j++)
{
while (root[j]==NULL)
{
j++;
}
Tree[i].val = root[j];
}
Tree[0].children.push_back(&Tree[1]);
Tree[0].children.push_back(&Tree[2]);
Tree[0].children.push_back(&Tree[3]);
Tree[1].children.push_back(&Tree[4]);
Tree[1].children.push_back(&Tree[5]);
Solution todo;
//N叉树的前序遍历
vector<int> result = todo.preorder(Tree);
//前序遍历的结果 打印
for (auto it = result.begin();it!=result.end();it++)
{
cout<<" "<<*it;
}
}
三、运行结果:
结果中,打印出的enter 和 Leave 是 深度优先遍历的 进入 和 回溯 的节点。
在 for 循环里面和外面 唯一的区别就 是对根节点的处理。
如果更改成在for循环里面打印,结果如下:
class Solution {
public:
vector<int> preorder(Node* root) {
if (root == NULL) return {};
childarr.push_back(root->val);
//在 for 循环里 打印
for (Node* child : root->children)
{
cout << "enter:" << child->val << endl;
preorder(child);
cout << "Leave:" << child->val << endl;
}
return childarr;
}
private:
vector<int> childarr;
};