题目详述
给定一个 N 叉树,返回其节点值的前序遍历。
解法一
递归。时间复杂度:O(n),空间复杂度:O(logn)
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> list = new ArrayList<>();
helper(root, list);
return list;
}
public void helper(Node root, List list) {
if (root == null) return;
int s = root.children.size();
list.add(root.val);
for (int i = 0; i < s; i++) helper(root.children.get(i), list);
}
}
解法二
迭代。时间复杂度:O(n),空间复杂度:O(n)
注意:
这里用到了一个函数。将其孩子节点逆序。
Collections.reverse(List);
class Solution {
public List<Integer> preorder(Node root) {
if (root == null) return new ArrayList();
LinkedList<Integer> ans = new LinkedList<>();
LinkedList<Node> stack = new LinkedList<>();
stack.addLast(root);
while (!stack.isEmpty()) {
Node temp = stack.pollLast();
ans.add(temp.val);
Collections.reverse(temp.children);
for (Node node : temp.children)
if (node != null) stack.add(node);
}
return ans;
}
}