【leetcode】589. N-ary Tree Preorder Traversal
2024-08-31 16:45:26
题目:
Given an n-ary tree, return the preorder traversal of its nodes' values.
For example, given a 3-ary
tree:
Return its preorder traversal as: [1,3,5,6,2,4]
.
Note:
Recursive solution is trivial, could you do it iteratively?
1. Recursive solution:
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children; Node() {} Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> preorder(Node* root) {
vector<int> order = {};
if (root) {
traversal(root, order);
} return order;
} void traversal(Node* root, vector<int> &order) {
order.push_back(root->val);
int num = root->children.size();
for (int i = 0; i < num; i++) {
traversal(root->children.at(i), order);
}
}
};
2. Iterative solution:
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children; Node() {} Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> preorder(Node* root) {
vector<int> order = {};
stack<Node*> nodeStack;
if (root) {
nodeStack.push(root);
} while (!nodeStack.empty()) {
Node* node = nodeStack.top();
nodeStack.pop();
order.push_back(node->val);
int num = node->children.size();
for (int i = num - 1; i >= 0; i--) {
nodeStack.push(node->children.at(i));
}
} return order;
} };
最新文章
- js:给定两个数组,如何判断他们的相对应下标的元素类型是一样的
- 跟着老男孩教育学Python开发【第二篇】:Python基本数据类型
- 小白Linux入门 四
- javascript-代理模式
- Linux(Centos6.5) Nginx 安装
- Single Responsibility Principle 单一职责原则
- CreateJSのTweenJS、SoundJS、PreloadJS
- BZOJ1845 : [Cqoi2005] 三角形面积并
- POJ 1741 树上的点分治
- Spring AOP 实现写事件日志功能
- Gatling的进阶二
- OGG-01224 Bad file number
- @RestController
- 用JS做图片轮播
- STC15?MSP430?ARM?DSP?
- webservice跨域上传图片
- DEV TdxLayoutGroup设置tab
- [js高手之路]深入浅出webpack系列2-配置文件webpack.config.js详解
- Flex中利用单选按钮切换柱状图横纵坐标以及描述
- Linux神奇命令之---tar
热门文章
- nginx 篇
- 在UE4C++中的宏
- exit命令
- 推荐 11 个好用的 JS 动画库
- python skimage图像处理(二)
- C#中得到每周,每月,每季,每年的年初末日期
- 【转发】jquery实现自动打开新的页签
- pd.ExcelWriter(to_excel)保存结果到已存在的excel文件中
- 【转载】 TensorFlow tf.app&;tf.app.flags用法介绍
- 我最近买的书里面带的CD盘,放电脑里后,说是0字节,但是可以播放,不能把里面的东西复制出来