Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. #From dailycodingproblem.com
  2. #Problem from 5.9.2019
  3. #My solution
  4.  
  5. #Good morning! Here's your coding interview problem for today.
  6.  
  7. #This problem was asked by Google.
  8.  
  9. #Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.
  10.  
  11. #For example, given the following Node class
  12.  
  13. class Node:
  14. def __init__(self, val, left=None, right=None):
  15. self.val = val
  16. self.left = left
  17. self.right = right
  18.  
  19. #The following test should pass:
  20.  
  21. def test ():
  22. node = Node('root', Node('left', Node('left.left')), Node('right'))
  23. assert deserialize(serialize(node)).left.left.val == 'left.left'
  24.  
  25.  
  26. def serialize( node ):
  27. nodes = []
  28. address_to_id = { id(node) : 1 }
  29. stack = [node]
  30. while stack:
  31. p = stack.pop()
  32. def app_child(ch):
  33. if None != ch:
  34. stack.append( ch )
  35. if id(ch) not in address_to_id:
  36. address_to_id[id(ch)] = len(address_to_id) + 1
  37. return address_to_id[id(ch)]
  38. return 0;
  39. nodes.append( (
  40. address_to_id[id(p)],
  41. p.val,
  42. app_child(p.left),
  43. app_child(p.right)
  44. ) )
  45. return repr(nodes)
  46.  
  47. def deserialize( encoding ):
  48. node_map = {}
  49. for ( n_id, n_val, n_left, n_right ) in reversed(eval(encoding)):
  50. def get_node(i):
  51. if i == 0:
  52. return Node
  53. else:
  54. assert( i in node_map )
  55. return node_map[i]
  56. node_map[n_id] = Node( n_val, get_node(n_left), get_node(n_right) )
  57. assert( 1 in node_map )
  58. return node_map[1]
  59.  
  60.  
  61.  
  62. test()
  63. print ("OK")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement