链接:
https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
描述:
示例:
代码:
/*
// 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 _preorder(const Node* root, vector<int> & res) {
if (root == nullptr) return;
res.push_back(root->val);
for (auto & ch : root->children)
_preorder(ch, res);
}
vector<int> preorder(Node* root) {
vector<int> res;
_preorder(root, res);
return res;
}
};
题目解析:
这个题类似于二叉树的前序遍历
void _preorderTraversal(struct TreeNode* root, int* res, int* resSize) {
if (root == NULL)
return;
res[(*resSize)++] = root->val;
_preorderTraversal(root->left, res, resSize);
_preorderTraversal(root->right, res, resSize);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
int* res = malloc(sizeof(int) * 100);
*returnSize = 0;
_preorderTraversal(root, res, returnSize);
return res;
}