1. Code
class FindElements:
def __init__(self, root: TreeNode):
self.values = {'0' : 0} # The dictionary to store the values of the modified tree.
root.val = 0
self.editNode(root) # Modify the values of the tree.
def find(self, target: int) -> bool:
if str(target) in self.values: # Check whether the dictionary has a value or not.
return True
else:
return False
def editNode(self, node):
if node.left: # If the node has left, modify the value of the left node and save it in the dictionary.
node.left.val = 2*node.val + 1
self.values[str(node.left.val)] = 0
self.editNode(node.left)
if node.right: # If the node has right, modify the value of the right node and save it in the dictionary.
node.right.val = 2*node.val + 2
self.values[str(node.right.val)] = 0
self.editNode(node.right)
2. Result
Runtime : 72 ms(100.00%), Memory usage : 19.7 MB(30.73%)
(Runtime can be different by a system even if it is a same code.)