算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 N 叉树的前序遍历,我们先来看题面:
https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
Given the root of an n-ary tree, return the preorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
给定一个 n 叉树的根节点 root ,返回 其节点值的 前序遍历 。
n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。
和二叉树的前序遍历类似,只是我们需要将每一个结点的所有孩子从左到右进行一遍遍历。递归代码非常简单。
class Solution {
public:
vector<int> num;
vector<int> preorder(Node* root) {
if(root==NULL) return num; //特例
num.emplace_back(root->val); //加入元素
//前序遍历
for(Node* t : root->children)
{
preorder(t);
}
return num;
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文:
LeetCode1-580题汇总,希望对你有点帮助!
LeetCode刷题实战581:最短无序连续子数组
LeetCode刷题实战582:杀掉进程
LeetCode刷题实战583:两个字符串的删除操作
LeetCode刷题实战584:寻找用户推荐人
LeetCode刷题实战585:2016年的投资
LeetCode刷题实战586:订单最多的客户
LeetCode刷题实战587:安装栅栏
LeetCode刷题实战588:设计内存文件系统