Back to problems

Tree Diameter / Longest Path

Algorithm · Meta · Medium

Requirements Input: either a binary tree (LC 543), represented by TreeNode nodes with val, left, and right fields and passed to diameterOfBinaryTree(root: TreeNode None) -> int, or a general N-ary tree (LC 1245), represented by Node nodes with val and children fields and passed to diameter(root: Node None) -> int. Output: the edge count of the longest route connecting any pair of nodes. Examples LC 543: tree [7,4,9,2,6] → 3 (a longest route is 2→4→7→9, and 6→4→7→9 has the…

Checking your access…