题目:

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;
} };

  

最新文章

  1. js:给定两个数组,如何判断他们的相对应下标的元素类型是一样的
  2. 跟着老男孩教育学Python开发【第二篇】:Python基本数据类型
  3. 小白Linux入门 四
  4. javascript-代理模式
  5. Linux(Centos6.5) Nginx 安装
  6. Single Responsibility Principle 单一职责原则
  7. CreateJSのTweenJS、SoundJS、PreloadJS
  8. BZOJ1845 : [Cqoi2005] 三角形面积并
  9. POJ 1741 树上的点分治
  10. Spring AOP 实现写事件日志功能
  11. Gatling的进阶二
  12. OGG-01224 Bad file number
  13. @RestController
  14. 用JS做图片轮播
  15. STC15?MSP430?ARM?DSP?
  16. webservice跨域上传图片
  17. DEV TdxLayoutGroup设置tab
  18. [js高手之路]深入浅出webpack系列2-配置文件webpack.config.js详解
  19. Flex中利用单选按钮切换柱状图横纵坐标以及描述
  20. Linux神奇命令之---tar

热门文章

  1. nginx 篇
  2. 在UE4C++中的宏
  3. exit命令
  4. 推荐 11 个好用的 JS 动画库
  5. python skimage图像处理(二)
  6. C#中得到每周,每月,每季,每年的年初末日期
  7. 【转发】jquery实现自动打开新的页签
  8. pd.ExcelWriter(to_excel)保存结果到已存在的excel文件中
  9. 【转载】 TensorFlow tf.app&amp;tf.app.flags用法介绍
  10. 我最近买的书里面带的CD盘,放电脑里后,说是0字节,但是可以播放,不能把里面的东西复制出来