给定一个 N 叉树,返回其节点值的前序遍历。
例如,给定一个 3叉树
:
img
返回其前序遍历: [1,3,5,6,2,4]
。
递归思想的解决
import java.util.ArrayList;
import java.util.List;
public class Preordertest4 {
public static void main(String[] args) {
Node node = new Node(1);
Node node2 = new Node(3);
Node node3 = new Node(2);
Node node4 = new Node(4);
Node node5 = new Node(5);
Node node6 = new Node(6);
List<Node> nodeList1 = new ArrayList<>();
List<Node> nodeList2 = new ArrayList<>();
nodeList2.add(node5);
nodeList2.add(node6);
nodeList1.add(node2);
nodeList1.add(node3);
nodeList1.add(node4);
node2.children = nodeList2;
node.children = nodeList1;
List<Integer> list = preorder(node);
System.out.println("list = " + list);
}
public static List<Integer> preorder(Node root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
dfs(root, list);
return list;
}
private static void dfs(Node root, List<Integer> list) {
if (root == null) {
return;
}
list.add(root.val);
if (root.children == null) {
return;
}
List<Node> children = root.children;
for (Node node : children
) {
dfs(node, list);
}
}
static 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;
}
}
}
对于本题,解决的思路是利用递归的思路进行解决。