Here is an algorithm that should do what you need. It assumes your data is ok, so it runs in O (n).
First you need a node that looks like this:
class Node { Node Parent; List<Node> Children = new List<Node>(); int NodeId; string Data; public Node(NodeRow row) { ... } }
- Download the first line as
current
. - Download the following line; compare
newRow.ParentNodeId
with current.NodeId
. - Until you find a match, set
current = current.Parent
- Add
newRow
to current.Children
and set current
to a new line. - Go to step 2.
What is it! If your data is properly structured, you do not need to do any additional null
checks.
Example:
Node CreateTree(IEnumerable<NodeRow> rows) { Node root = null; Node current = null; foreach (var row in rows) { // Root: if (root == null) { root = current = new Node(row); continue; } // Traverse up the tree until the parent is found: while (row.ParentNodeId != current.NodeId) { current = current.Parent; } // Add the new node as a child of the current one: var rowNode = new Node(row); rowNode.Parent = current; current.Children.Add(rowNode); current = rowNode; } return root; }
source share