-
Notifications
You must be signed in to change notification settings - Fork 17
/
find-elements-in-a-contaminated-binary-tree.py
59 lines (45 loc) · 1.49 KB
/
find-elements-in-a-contaminated-binary-tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class FindElements:
def __init__(self, root: TreeNode):
self.root = root
# Setting of values is not necessary
# if not self.root:
# return
# else:
# self.root.val = 0
# stack = [self.root]
# while stack:
# old_stack = stack
# stack = []
# for node in stack:
# if node.left:
# stack.append(node.left)
# node.left.val = node.val * 2 + 1
# if node.right:
# stack.append(node.right)
# node.right.val = node.val * 2 + 2
def find(self, target: int) -> bool:
def traverse_back(val):
if val == 0:
return self.root
elif val % 2 == 1:
prev = traverse_back((val - 1) / 2)
if not prev:
return None
if prev.left:
return prev.left
else:
prev = traverse_back((val - 2) / 2)
if not prev:
return None
if prev.right:
return prev.right
return traverse_back(target) is not None
# Your FindElements object will be instantiated and called as such:
# obj = FindElements(root)
# param_1 = obj.find(target)