leetcode1261 Find Elements in a Contaminated Binary Tree

 1 """
 2 Given a binary tree with the following rules:
 3     root.val == 0
 4     If treeNode.val == x and treeNode.left != null, then treeNode.left.val == 2 * x + 1
 5     If treeNode.val == x and treeNode.right != null, then treeNode.right.val == 2 * x + 2
 6 Now the binary tree is contaminated, which means all treeNode.val have been changed to -1.
 7 You need to first recover the binary tree and then implement the FindElements class:
 8     FindElements(TreeNode* root) Initializes the object with a contamined binary tree, you need to recover it first.
 9     bool find(int target) Return if the target value exists in the recovered binary tree.
10 Example 1:
11 Input
12 ["FindElements","find","find"]
13 [[[-1,null,-1]],[1],[2]]
14 Output
15 [null,false,true]
16 Explanation
17 FindElements findElements = new FindElements([-1,null,-1]);
18 findElements.find(1); // return False
19 findElements.find(2); // return True
20 Example 2:
21 Input
22 ["FindElements","find","find","find"]
23 [[[-1,-1,-1,-1,-1]],[1],[3],[5]]
24 Output
25 [null,true,true,false]
26 Explanation
27 FindElements findElements = new FindElements([-1,-1,-1,-1,-1]);
28 findElements.find(1); // return True
29 findElements.find(3); // return True
30 findElements.find(5); // return False
31 Example 3:
32 Input
33 ["FindElements","find","find","find","find"]
34 [[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]
35 Output
36 [null,true,false,false,true]
37 Explanation
38 FindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);
39 findElements.find(2); // return True
40 findElements.find(3); // return False
41 findElements.find(4); // return False
42 findElements.find(5); // return True
43 """
44 class TreeNode:
45     def __init__(self, x):
46         self.val = x
47         self.left = None
48         self.right = None
49 
50 class FindElements:
51     def __init__(self, root):
52         self.array = []  # !!!保存结点出现的值,注意self. 私有成员
53         if root != None:  # 调用递归函数
54             self.recover_tree(root, 0)
55     def recover_tree(self, root, v):  # 递归调用
56         root.val = v
57         self.array.append(v)
58         if root.left != None:
59             self.recover_tree(root.left, 2 * v + 1)
60         if root.right != None:
61             self.recover_tree(root.right, 2 * v + 2)
62     def find(self, target: int) -> bool:
63         return target in self.array  # 再结果数组里找

猜你喜欢

转载自www.cnblogs.com/yawenw/p/12284774.html