Problem 484781 · medium · Level 04 Non-Linear Data Structures

Longest Cable Run in a Network Tree

n-ary tree · postorder · dynamic programming on trees

A building's network is an N-ary tree of switches (Node objects with val and children); each parent-child link is one cable. Return the length, in cables, of the longest path between any two switches (the path may pass through a switch's parent and does not have to touch the root). A tree with a single switch has answer 0, and so does an empty tree.

Examples

Input:  root = Node(1, [Node(2, [Node(4), Node(5, [Node(7)])]), Node(3, [Node(6)])])
Output: 5
Explanation: 7 - 5 - 2 - 1 - 3 - 6 uses five cables.

Input:  root = Node(1, [Node(2), Node(3), Node(4)])
Output: 2

Constraints

  • 0 <= number of nodes <= 10**4, depth up to 1500 (an iterative solution is safer)
  • Target: O(n) time

Goals

  • Compute subtree heights bottom-up in an N-ary tree
  • Combine the two tallest child subtrees at every node to find the longest path
Starting Python…