[LeetCode] N-ary Tree Preorder Traversal N叉树的前序遍历
2023-09-11 14:21:37 时间
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?
这道题让我们求N叉树的前序遍历,有之前那道Binary Tree Preorder Traversal的基础,知道了二叉树的前序遍历的方法,很容易就可以写出N叉树的前序遍历。先来看递归的解法,主要实现一个递归函数即可,判空之后,将当前结点值加入结果res中,然后遍历子结点数组中所有的结点,对每个结点都调用递归函数即可,参见代码如下:
解法一:
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来辅助,需要注意的是,如果使用栈的话,我们遍历子结点数组的顺序应该是从后往前的,因为栈是后进先出的顺序,所以需要最先遍历的子结点应该最后进栈,参见代码如下:
解法二:
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; } };
类似题目:
Binary Tree Preorder Traversal
N-ary Tree Level Order Traversal
N-ary Tree Postorder Traversal
参考资料:
https://leetcode.com/problems/n-ary-tree-preorder-traversal/
相关文章
- Java实现 LeetCode 832 翻转图像(位运算)
- Java实现 LeetCode 769 最多能完成排序的块(单向遍历)
- Java实现 LeetCode 701 二叉搜索树中的插入操作(遍历树)
- Java实现 LeetCode 500 键盘行
- Java实现 LeetCode 498 对角线遍历
- Java实现 LeetCode 472 连接词
- Java实现 LeetCode 1013 将数组分成和相等的三个部分
- Java实现 LeetCode 332 重新安排行程
- Java实现 LeetCode 103 二叉树的锯齿形层次遍历
- Java实现 LeetCode 107 二叉树的层次遍历 II(二)
- Java实现 LeetCode 106 从中序与后序遍历序列构造二叉树
- Java实现 LeetCode 99 恢复二叉搜索树
- Java实现 LeetCode 39 组合总和
- 每日一道 LeetCode (32): 验证回文串
- 每日一道 LeetCode (23):二叉树的层次遍历 II
- LeetCode: 103_Binary Tree Zigzag Level Order Traversal | 二叉树Zigzag层次遍历 | Medium
- LeetCode:94_Binary Tree Inorder Traversal | 二叉树中序遍历 | Medium
- LeetCode:144_Binary Tree Preorder Traversal | 二叉树的前序遍历 | Medium
- 【二叉树】LeetCode 102. 二叉树的层序遍历【中等】
- (“树” 之 前中后序遍历 ) 94. 二叉树的中序遍历 ——【Leetcode每日一题】
- 【LeetCode 9】回文数
- Leetcode 1047. 删除字符串中的所有相邻重复项
- Leetcode 最长连续序列
- 【Leetcode刷题Python】矿泉水问题
- 【Leetcode刷题Python】103. 二叉树的锯齿形层序遍历
- 【Leetcode刷题Python】 LeetCode 2038. 如果相邻两个颜色均相同则删除当前颜色
- 【LeetCode】102. 二叉树的层序遍历