Approach #1: Recursion [Accepted]
We can think of any path (of nodes with the same values) as up to two arrows extending from it's root.
Specifically, the root of a path will be the unique node such that the parent of that node does not appear in the path, and an arrow will be a path where the root only has one child node in the path.
Then, for each node, we want to know what is the longest possible arrow extending left, and the longest possible arrow extending right? We can solve this using recursion.
arrow_length(node) be the length of the longest arrow that extends from the
node. That will be
1 + arrow_length(node.left) if
node.left exists and has the same value as
node. Similarly for the
While we are computing arrow lengths, each candidate answer will be the sum of the arrows in both directions from that node. We record these candidate answers and return the best one.
Time Complexity: , where is the number of nodes in the tree. We process every node once.
Space Complexity: , where is the height of the tree. Our recursive call stack could be up to layers deep.
Analysis written by: @awice