题目:
给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树 :
返回其后序遍历: [5,6,3,2,4,1].
说明: 递归法很简单,你可以使用迭代法完成此题吗?
解法1:递归
public List<Integer> postorder(Node root) {
ArrayList<Integer> result = new ArrayList<>();
recursive(root,result);
return result;
}
private void recursive(Node root, ArrayList<Integer> result) {
if (root==null)return;
if (!root.children.isEmpty()){
for (Node n:root.children){
recursive(n,result);
}
}
result.add(root.val);
}
时间复杂度:On
空间复杂度:On
解法2:stack
/**
* 思路:
* 用ArrayList实现
* 根右左记录,之后反转结果集
*/
public List<Integer> postorder(Node root) {
ArrayList<Integer> result = new ArrayList<>();
if (root==null)return result;
ArrayDeque<Node> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()){
Node pop = stack.pop();
result.add(pop.val);
if (!pop.children.isEmpty()){
for (Node n:pop.children){
stack.push(n);
}
}
}
Collections.reverse(result);
return result;
}
时间复杂度:On^2
空间复杂度:On
/**
* 思路:
* 用ArrayList实现
* 根右左入栈,每次把children赋值为null,没有children加入到结果集
*/
public List<Integer> postorder(Node root) {
ArrayList<Integer> result = new ArrayList<>();
if (root==null)return result;
ArrayDeque<Node> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()){
Node pop = stack.pop();
if (pop.children!=null){
stack.push(pop);
Collections.reverse(pop.children);
for (Node n:pop.children){
stack.push(n);
}
pop.children=null;
}else {
result.add(pop.val);
}
}
return result;
}
时间复杂度:On^2
空间复杂度:On
/**
* 思路:
* 用LinkedList实现
* 链表实现,根右左加入链表的头部
*/
public List<Integer> postorder(Node root) {
LinkedList<Integer> result = new LinkedList<>();
if (root==null)return result;
ArrayDeque<Node> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()){
Node pop = stack.pop();
result.offerFirst(pop.val);
for (Node n:pop.children){
stack.push(n);
}
}
return result;
}
时间复杂度:On^2
空间复杂度:On