1

In a treenode levels will be increased in ascending order I want to write a function so that it will reverse the level of a tree I know that I should get the depth of the tree and then compute the

depth-selectednodeLevel

so that it will result the tree levels in descending order I didn't know how to get the depth of the tree,the property LastNode will give the last child of the node and I coudn't use it for depth because it will return lastNode of just for that level not the lower ones.

for example a usual treenodes levels are as follows

|0|
 |
|1|
 |
|2|
 |
|3|

I want to make it

 |3|
  |
 |2|
  |
 |1|
  |
 |0|

1 Answer 1

0

Seems like all you need to solve the issue is finding the depth of the tree, so to do that you can use simple recursion.

Psuedo-code:

int GetDepth(Node node)
{
    return node.HasChilds ? node.Childs.Max(GetDepth) : node.Level;
}

And in C#, assuming you use the TreeNode class to represent nodes:

public int GetDepth(TreeNode node)
{
    return node.Nodes.Count == 0
        ? node.Level
        : node.Nodes.Cast<TreeNode>().Select(this.GetDepth).Max();
}

Usage:

var depth = GetDepth(myTree.Root);

And if you don't have the Level property of every node, you can just add a parameter like so:

public int GetDepth(TreeNode node, int depth)
{
    return node.Nodes.Count == 0
        ? depth
        : node.Nodes.Cast<TreeNode>()
              .Select(x => this.GetDepth(x, depth + 1)).Max();
}

Usage:

var depth = GetDepth(myTree.Root, 0);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.