如题,N叉树的前序遍历和后续遍历。leetcode上两道题挨着,让用迭代法。我先给一下递归的代码:
前序:
/*
// 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 {
List<Integer> l=new ArrayList<>();
public List<Integer> preorder(Node root) {
if(root==null){
return l;
}
l.add(root.val);
if(root.children!=null){
for(Node n:root.children){
preorder(n);
}
}
return l;
}
}
后续:
class Solution {
public List<Integer> postorder(Node root) {
post(root);
return l;
}
Link