前序遍历,(先添加当前结点到结果llist,再遍历当前结点的children list。)
/*
// 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> list = new ArrayList<Integer>();
public List<Integer> preorder(Node root) {
if (root == null)
return list;
list.add(root.val);
for (Node node : root.children)
preorder(node);
return list;
}
}
后续遍历(先遍历当前结点的children list。再添加当前结点到结果list)
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> postorder(Node root) {
if (root == null) return list;
for (Node node : root.children){
postorder(node);
}
list.add(root.val);
return list;
}
}