前言
和昨天的前序遍历基本一致
题目
源码
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
LinkedList <Integer> ans=new LinkedList<>();
public List<Integer> postorder(Node root) {
// 方法1,迭代
// LinkedList<Node> stack=new LinkedList<>();
// LinkedList<Integer> ans=new LinkedList<>();
// if(root==null){
// return ans;
// }
// stack.add(root);
// while(!stack.isEmpty()){
// Node node = stack.pollLast();
// ans.addFirst(node.val);
// for(Node item:node.children){
// if(item!=null){
// stack.add(item);
// }
// }
// }
// return ans;
// 方法2递归
if(root==null){
return ans;
}
for(Node item:root.children){
if(item!=null){
postorder(item);
}
}
ans.addLast(root.val);
return ans;
}
}