CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jan 2009
    Posts
    25

    Height of weighted tree

    Hi, I'm trying to compute the leaf furthest from the root of a weighted tree (meaning the sum total of the weights of every edge used to get to that leaf is the greatest) Any suggested algorithms I could take a look at? (Looking for some optimal solutions)

    Thanks

  2. #2
    Join Date
    Mar 2009
    Posts
    19

    Re: Height of weighted tree

    Well, normally, to find the depth of a tree, we do something like this:

    Code:
    int GetDepth(Node * node)
    {
    	//this example doesn't take into account trees with just one child
    	//but that's something you'll need to worry about
    	if(!(node->right || node->left))
    	{
    		//a tree with one node has height zero
    		return 0;
    	}
    	else
    	{
    		return std::max(GetDepth(node->right), GetDepth(node->left)) + 1;
    	}
    }
    It shouldn't be too hard to extend that to your problem. Instead of adding 1, you'd add the edge's weight. And you'd have to have some way of tracking the current deepest leaf (either with an out-paramo or returning a struct with both the depth and the node, or something else).

    Regardless, the number of lines of code should be quite small.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured