给定一个 n 叉树的根节点 root
,返回 其节点值的 前序遍历 。
n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null
分隔
正常版(递归)
class Solution {
List<Integer> ans = new ArrayList<>();
public List<Integer> preorder(Node root) {
dfs(root);
return ans;
}
void dfs(Node root) {
if (root == null) return ;
ans.add(root.val);
for (Node node : root.children) dfs(node);
}
}
大佬其他解法:
迭代
针对本题,使用「栈」模拟递归过程。
迭代过程中记录 (node = 当前节点, cnt = 当前节点遍历过的子节点数量) 二元组,每次取出栈顶元素,如果当前节点是首次出队(当前遍历过的子节点数量为 cnt = 0cnt=0),则将当前节点的值加入答案,然后更新当前元素遍历过的子节点数量,并重新入队,即将 (node, cnt + 1)(node,cnt+1) 入队,以及将下一子节点 (node.children[cnt], 0)(node.children[cnt],0) 进行首次入队。
作者:AC_OIer
链接:https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/solution/gong-shui-san-xie-shu-de-sou-suo-yun-yon-pse1/
来源:力扣(LeetCode)
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> ans = new ArrayList<>();
Deque<Object[]> d = new ArrayDeque<>();
d.addLast(new Object[]{root, 0});
while (!d.isEmpty()) {
Object[] poll = d.pollLast();
Node t = (Node)poll[0]; Integer cnt = (Integer)poll[1];
if (t == null) continue;
if (cnt == 0) ans.add(t.val);
if (cnt < t.children.size()) {
d.addLast(new Object[]{t, cnt + 1});
d.addLast(new Object[]{t.children.get(cnt), 0});
}
}
return ans;
}
}