With any tree structure, searching is going to use relatively the same algorithm (depth-first recursion if unsorted, or simple tree-searching if sorted (like binary search tree)). When you insert, all you need to do is assign the new node's .parent
to the parent. Then assign the new node's .parent.child[1]
to the new node (thus linking the parent to the child). Then, check the other children of the parent node to assign your new node's siblings (if any).
Okay, so here's some pseudocode (mostly like java -- sorry, it's what i've been writing today) that will implement node creation and the series of assignments to maintain it in a tree structure, using the second example in the link you provided:
(node source):
class Node {
// generic data store
public int data;
public Node parent;
public Node siblings;
public Node children;
}
(tree source):
class NewTree {
// current node
public Node current;
// pointer to root node
public Node root;
// constructor here
// create new node
public boolean insert(int data) {
// search for the node which is immediately BEFORE where the new node should go
// remember that with duplicate data values, we can just put the new node in
// front of the chain of siblings
Node neighbor = this.search(data);
// if we've found the node our new node should follow, create it with the
// found node as parent, otherwise we are creating the root node
// so if we're creating the root node, we simply create it and then set its
// children, siblings, and parent to null
// i think this is the part you're having trouble with, so look below for a
// diagram for visual aid
}
public Node search(int target) {
// basically we just iterate through the chain of siblings and/or children
// until this.current.children is null or this.current.siblings is null
// we need to make certain that we also search the children of
// this.index.sibling that may exist (depth-first recursive search)
}
}
When we find the spot (using search()) where our new node should go, we need to reassign the parent, children, and siblings "links" inside the new node to its new parent, children, and siblings. For example, we take this:
A-|
|
B-C-|
| |
| F-G-|
| |
| -
|
D-E-|
| |
- H-|
|
-
And we will insert a new node (X) where F is. This is just to illustrate how we reassign each of the new node's links. The finer details may be slightly different, but what's important here is the implementation example of the link reassignment:
A-|
|
B-C-|
| |
| X-F-G-|
| | |
| - -
|
D-E-|
| |
- H-|
|
-
What we do is: 1) Create X. 2) Assign x.parent to c. 3) Reassign c.children to x. 4) Assign x.siblings to f. This inserts a new node (be mindful that an insertion is different than a sort and your tree may need resorting if you explicitly require a specific ordering).