题目


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 {
public List<Integer> preorder(Node root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
Node cur = stack.pop();
res.add(cur.val);
for (int i = cur.children.size() - 1; i >= 0; i--) {
stack.push(cur.children.get(i));
}
}
return res;
}
}
方法二:递归
class Solution {
List<Integer> res = new ArrayList<>();
public List<Integer> preorder(Node root) {
dfs(root);
return res;
}
public void dfs(Node root) {
if (root == null) {
return;
}
res.add(root.val);
for (Node node : root.children) {
dfs(node);
}
}
}