题目地址:
https://leetcode.com/problems/n-ary-tree-preorder-traversal/
前序遍历多叉树。
法1:分治法
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<Integer> preorder(Node root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
res.add(root.val);
if (root.children != null) {
for (Node child : root.children) {
res.addAll(preorder(child));
}
}
return res;
}
}
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;
}
};
时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( h ) O(h) O(h), h h h为树的高度。
法2:DFS
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<Integer> preorder(Node root) {
List<Integer> res = new ArrayList<>();
preorderTraversal(root, res);
return res;
}
private void preorderTraversal(Node root, List<Integer> res) {
if (root == null) {
return;
}
res.add(root.val);
if (root.children != null) {
for (Node child : root.children) {
preorderTraversal(child, res);
}
}
}
}
时空复杂度与上同。
法3:用栈模拟DFS
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class Solution {
public List<Integer> preorder(Node root) {
List<Integer> res = new ArrayList<>();
Deque<Node> stack = new LinkedList<>();
if (root == null) {
return res;
}
stack.push(root);
while (!stack.isEmpty()) {
Node x = stack.pop();
res.add(x.val);
if (x.children != null) {
for (int i = x.children.size() - 1; i >= 0; i--) {
stack.push(x.children.get(i));
}
}
}
return res;
}
}
时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( k h ) O(kh) O(kh), k k k为这棵树每一层的节点的最大分叉数, h h h是树的高度。由于用栈模拟递归的时候,需要存储当前状态,也就是将来要访问的节点都需要先push到栈里,所以空间复杂度是分叉数之和。