I need to compute the diameter of an N-ary tree represented as a Binary Tree (left-child, right-sibling representation). Can someone give me an idea or a pseudocode?
My best attempt was to add a +1 to the result whenever there was a left child, but I do not think that this is enough.
The idea is to traverse the tree in a post-order traversal, collecting two pieces of information about each node:
When this information is known for each of the children of a given node, then you can find out which are the two subtrees with the greatest heights. The sum of these two heights represents a candidate for a diameter for the current node. It should be compared with the diameters retrieved for each of the children. The greatest of these all is the diameter of the current node.
And so the diameter can bubble up out of recursion.
Here is an (runnable) implementation in JavaScript that executes the process on this example n-ary tree:
Note that the longest path in this tree connects node 6 with node 10, giving a path length of 6, which is the diameter of the whole tree.
If we picture the data structure, not with the above edges, but with its links to nodes, then it looks like this (downward arrows =
firstChild
; rightward arrows =nextSibling
):Here is an implementation to solve the problem with that data structure: