树和二叉树_5
一、leetcode-589
N叉树的前序遍历
给定一个 n 叉树的根节点 root ,返回 其节点值的 前序遍历 。
n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。
样例输入:root = [1,null,3,2,4,null,5,6]
样例输出: [1,3,5,6,2,4]
二、题解
1.引库
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <stack>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <vector>
using namespace std;
2.代码
- 递归实现前序遍历
- 采用封装减少数据递归内部传递次数
/*
// Definition for a 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;
}
};
*/
class Solution {
public:
vector<int> preorder(Node* root) {
if(root==NULL) return vector<int>();
vector<int> ans;
ans.push_back(root->val);
for(auto x:root->children){
vector<int> temp=preorder(x);
for(auto y:temp) ans.push_back(y);
}
return ans;
}
};
//采用封装减少数据递归内部传递次数
class Solution {
public:
void __preorder(Node *root, vector<int> &ans){
if(root==NULL) return ;
ans.push_back(root->val);
for(auto x:root->children){
__preorder(x,ans);
}
return ;
}
vector<int> preorder(Node* root) {
vector<int> ans;
__preorder(root,ans);
return ans;
}
};
3.思考
进阶:递归法很简单,你可以使用迭代法完成此题吗?