深度优先搜索
class Solution {
List<Integer> list = new LinkedList<>();
public List<Integer> postorder(Node root) {
if (root == null){
return list;
}
for (Node c : root.children){
postorder(c);
}
list.add(root.val);
return list;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
迭代
class Solution {
public List<Integer> postorder(Node root) {
List<Integer> list = new LinkedList<>();
Stack<Node> stack = new Stack<>();
if (root == null){
return list;
}
stack.push(root);
while (!stack.isEmpty()){
Node temp = stack.pop();
list.add(temp.val);
for (Node c : root.children){
stack.push(c);
}
}
Collections.reverse(list);
return list;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
原文地址:https://www.cnblogs.com/taoyuann/p/15918889.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。