Longest Univalue Path

Advanced

Welcome to an exciting coding challenge where you will explore a mystical forest of trees! Each tree in this forest has nodes, and these nodes love to carry values. Some trees are mysterious—parts of their branches have repeated values, forming a path of the same number! Your mission, should you choose to accept it, is to discover the longest path in a tree where every node along the path has the same value. Remember, the path need not go through the root of the tree and can be any connected branches with the same value.

Your Task:

  • You will be given a nested dictionary representing a binary tree.
  • Implement the function longest_univalue_path(tree_dict) that takes the nested dictionary and returns the length of the longest path where each node has the same value.
  • You need to build the tree from the nested dictionary within your function.

Example Tree Representations:

  1. For the tree:

         5
        / \
       4   5
      / \   \
     1   4   5
    

    The dictionary representation is:

    { 'value': 5, 'left': { 'value': 4, 'left': {'value': 1}, 'right': {'value': 4} }, 'right': { 'value': 5, 'right': {'value': 5} } }
    • The longest univalue path is 5 -> 5 -> 5, so the function should return 2.
  2. For the tree:

         1
        / \
       4   5
      / \   \
     4   4   5
    

    The dictionary representation is:

    { 'value': 1, 'left': { 'value': 4, 'left': {'value': 4}, 'right': {'value': 4} }, 'right': { 'value': 5, 'right': {'value': 5} } }
    • The longest univalue path is 4 -> 4 -> 4, so the function should return 2.
Geek
Inputs

Arg 1:

{"value":5,"left":{"value":4,"left":{"value":1},"right":{"value":4}},"right":{"value":5,"right":{"value":5}}}
Expected Output
2
Actual Output