I have a data structure that describes a tree. Nodes are ordered, with "depth" information, and knowing the order and the depth the tree can be reconstructed. I'm not entirely sure how to describe it so I'm hoping this small example will illustrate it
node #1, depth 0 // parent: none
node #2, depth 1 // parent: #1
node #3, depth 1 // parent: #1
node #4, depth 2 // parent: #3
node #5, depth 1 // parent: #1
node #6, depth 2 // parent: #5
(I added parent information in there for clarification. That's not part of the data structure.)
I'm trying to write an algorithm (in JS, if that's any help) that will iterate over each node and build a tree out of the data. I'm fairly recursion is the way to go but beyond that I'm not sure where to start. Any suggestions?
Edit: The way I see it, I have four cases:
- Node has depth 0 (initial case)
- Node has same depth as previous
- Node has greater depth as previous (should only be previous.depth+1)
- Node has less depth than previous
Here's my pseudo-JS-code so far:
process (nodes, 0);
process = function(nodes, i) {
cur = nodes[i], prev = nodes[i-1]
if cur.depth = 0 then cur.parent = null // case #1
else if cur.depth == prev.depth then cur.parent = prev.parent // case #2
else if cur.depth > prev.depth then cur.parent = prev // case #3
else // case #4... here's where I'm stuck.
if i <= nodes.length then process (nodes, i+1)
}