Advertisement
Guest User

Untitled

a guest
Nov 19th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1.  
  2.  
  3. class Node:
  4.     def __init__(self ,key):
  5.         self.key = key
  6.         self.child = []
  7.  
  8.  
  9. def longestUnivaluePath(root):
  10.     def arrow_length(node):
  11.         global ans
  12.        
  13.         child_lengths = [ arrow_length(child_node)  for child_node in node.child ]
  14.         child_arrows = [ (child_length+1) for child_node, child_length in zip(node.child, child_lengths) if child_node.key == node.key ]        
  15.         ans = max(child_arrows + [ans])
  16.  
  17.         return max(child_arrows) if child_arrows else 0
  18.  
  19.     arrow_length(root)
  20.     return ans
  21.  
  22.  
  23.  
  24.  
  25. root = Node(2)
  26. child_nodes = [Node(2), Node(1), Node(10), Node(3)]
  27. root.child = child_nodes
  28.  
  29. sub_child_nodes_2 = [Node(2), Node(2)]
  30. child_nodes[0].child = sub_child_nodes_2
  31.  
  32. sub_child_nodes_1 = [Node(2), Node(3)]
  33. child_nodes[1].child = sub_child_nodes_1
  34.  
  35. sub_child_nodes_10 = [Node(2), Node(3)]
  36. child_nodes[2].child = sub_child_nodes_10
  37.  
  38. sub_child_nodes_3 = [Node(2), Node(3)]
  39. child_nodes[3].child = sub_child_nodes_3
  40.  
  41. ans = 0
  42. print longestUnivaluePath(root)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement