tags:

views:

151

answers:

2

Hi there, I have an node object which specifies the node level

public class Node
{
    public int Level { get; set; }
}

I want to use an ordered list of nodes to construct a treeview

var nodes = new[]
{
    new Node(){Level = 0},
        new Node(){Level = 1},
        new Node(){Level = 1},
        new Node(){Level = 1},
            new Node(){Level = 2},
        new Node(){Level = 1},
            new Node(){Level = 2},
            new Node(){Level = 2},
                new Node(){Level = 3},
};

What is the most efficient way to do this.

Thanks

Rohan

A: 

Loop over your list of nodes. Starting with index 0, record that node's Level. At all subsequent indexes check the level against the last recorded level. If higher, add it as a subnode of the last added node. If lower, well.. if lower cases problems.. find the appropriate node to add it to.

Boo
A: 

Following on from Boo, you'll want to keep a stack of the nodes as you step to a higher level. If the level is higher on the current node, push the previous node onto the stack and use it as the parent. If the level is lower than the previous node, pop n nodes off the stack (n = previous_level - current_level) and use the new stack-top as the parent.

JJO