I have a university project where I need to implement an N-ary tree in dart.
This is my node so far
class Node {
Node parent; // parent of the current node
List<Node> children; // children of the current node
int id;
String actualMessage;
Node (int id, String actualMessage){
this.id=id;
this.actualMessage=actualMessage;
children = new List<Node>();
}
}
I am stuck on how I should implement the following methods. I will try to explain what I need with the following example
A is root and has 3 children : B, C and D. B has 2 children: E and F. E has 1 child: G.
Any code or info on how to do the above will be much appreciated. It's my third day where I am stuck on the same thing.
Thank you
Wow, that's a lot you're asking for :P
I've tried out the first 2 requirements and here is the code that can help you fulfil them.
Node root = new Node(0, "A"); // Your root node
I'll be showing the results of a Pre-Order traversal on the tree.
void addNode(Node parent, Node newNode){
newNode.parent = parent;
parent.children.add(newNode);
}
After running:
Node b = new Node(1, "B");
addNode(root, b);
Node e = new Node(2, "E");
addNode(b, e);
Pre-order traversal result:
Visited Node A
Visiting child:
Visited Node B
Visiting child:
Visited Node E
This agrees with your structure :D
void deleteNode(Node treeRoot, String message){
Node n = treeRoot;
if(message == n.actualMessage){
print("Deleted Node " +n.actualMessage);
n.parent.children.remove(n);
return;
}
for(int i = 0; i < n.children.length; i++){
deleteNode(n.children[i], message);
}
}
After Running:
deleteNode(root, "B");
Pre-order traversal result:
Deleted Node B
Visited Node A
Again, Seems to be working fine :D
Ill update this as soon as I get more time