Given an n-ary tree, return the preorder traversal of its nodes' values.html
For example, given a 3-ary
tree:node
Return its preorder traversal as: [1,3,5,6,2,4]
.数组
Note:函数
Recursive solution is trivial, could you do it iteratively?post
这道题让咱们求N叉树的前序遍历,有以前那道Binary Tree Preorder Traversal的基础,知道了二叉树的前序遍历的方法,很容易就能够写出N叉树的前序遍历。先来看递归的解法,主要实现一个递归函数便可,判空以后,将当前结点值加入结果res中,而后遍历子结点数组中全部的结点,对每一个结点都调用递归函数便可,参见代码以下:url
解法一:spa
class Solution { public: vector<int> preorder(Node* root) { vector<int> res; helper(root, res); return res; } void helper(Node* node, vector<int>& res) { if (!node) return; res.push_back(node->val); for (Node* child : node->children) { helper(child, res); } } };
咱们也能够使用迭代的解法来作,使用栈stack来辅助,须要注意的是,若是使用栈的话,咱们遍历子结点数组的顺序应该是从后往前的,由于栈是后进先出的顺序,因此须要最早遍历的子结点应该最后进栈,参见代码以下:code
解法二:htm
class Solution { public: vector<int> preorder(Node* root) { if (!root) return {}; vector<int> res; stack<Node*> st{{root}}; while (!st.empty()) { Node* t = st.top(); st.pop(); res.push_back(t->val); for (int i = (int)t->children.size() - 1; i >= 0; --i) { st.push(t->children[i]); } } return res; } };
相似题目:blog
Binary Tree Preorder Traversal
N-ary Tree Level Order Traversal
N-ary Tree Postorder Traversal
参考资料:
https://leetcode.com/problems/n-ary-tree-preorder-traversal/