Problem: 589. N 叉树的前序遍历
文章目录
思路
前序遍历,遇到空节点返回
解题过程
对每个节点进行遍历
Code
C++
/*
// 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:
void traversal(Node* cur, vector<int>& vec)
{//cur当前遍历节点,vec储存值
if (cur == NULL)
return;
vec.push_back(cur->val);//当前值储存(val节点所代表的值)(***把这一行移动到循环后面就变为后续遍历***)
for (Node* child : cur->children) //遍历每个子节点
traversal(child, vec);(***这个后面***)
}
vector<int> preorder(Node* root)
{
vector<int> result; //储存结果
traversal(root, result);
return result;
}
};