This is just a practice exercise, I'm trying to understand dynamic programming as deeply as I can. I solved this using recursion, though I am not sure if it will always work. If anyone could tell me a case in which my solution does not work. And I would also appreciate knowing the time/space complexities of this solution. knowing a binary tree is usually \$\mathcal{O}(n^2)\$, I believe my solution is \$\mathcal{O}(n)\$.
AKA. Please tell me how efficient my solution is, if at all. Thanks.
class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def __repr__(self): if self.left and self.right: return f"({self.value}, {self.left}, {self.right})" if self.left: return f"({self.value}, {self.left})" if self.right: return f"({self.value}, None, {self.right})" return f"({self.value})" map={} def dup_trees(root): if(root.left): print("left found") try: if map[root.value]: print("duplicate Left") except KeyError: map[root.value]= str(root.value)+','+str(root.left.value) if(root.right): print("right found") try: if map[root.value]: print("duplicate Right") except KeyError: map[root.value]= str(root.value)+','+str(root.left.value) elif(not root.left and not root.right): print("no left or right") try: if map[root.value]: print("duplicate Leaf") except KeyError: map[root.value]= str(root.value)+',X' if root.left: dup_trees(root.left) if root.right: dup_trees(root.right) n3_1 = Node(3) n2_1 = Node(2, n3_1) n3_2 = Node(3) n2_2 = Node(2, n3_2) n1 = Node(1, n2_1, n2_2) dup_trees(n1) print(map) # Looks like # 1 # / \ # 2 2 # / / # 3 3 # There are two duplicate trees # # 2 # / # 3 # and just the leaf # 3
dup_trees()
, inside theif(root.right)
, you storeroot.left.value
in the map. You also don't correctly handle the case where both left and right children are present, and you only store the immediate values, not the whole subtrees. You should use some larger test cases.\$\endgroup\$