In order to define a N-ary tree, we need to be able to store the Node value and its children – which is a list of the Node. And the Node type can be referenced recursively. See below Java Class Node:
class Node {
public Node(int val, Node[] children) {
this.val = val;
this.children = children;
}
public int getVal() {
return this.val;
}
public Node[] getChildren() {
return this.children;
}
private int val;
private Node[] children;
}
Then, we can create nodes first, and build a N-nary tree by linking them.
Node A = new Node(1, null);
Node B = new Node(2, null);
Node C = new Node(3, null);
Node root = new Node(0, new Node[]{A, B, C});
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Teaching Kids Programming - Find Root of N-Ary Tree using Hash Set
Next Post: Simple Blockchain Example in Java