You are given a contaminated binary tree where all TreeNode.val
have been changed to -1
. The tree follows these rules:
0
.x
, then:
2 * x + 1
.2 * x + 2
.Implement the FindElements
class:
FindElements(TreeNode* root)
: Initializes the object with a contaminated binary tree and recovers it.bool find(int target)
: Returns true
if the target
value exists in the recovered binary tree, otherwise returns false
.["FindElements","find","find"]
[[[-1]],[0],[1]]
[null,true,false]
FindElements findElements = new FindElements([-1]);
findElements.find(0); // returns True (root is always 0)
findElements.find(1); // returns False (no left or right child exists)
["FindElements","find","find","find","find","find"]
[[[-1,-1,-1,-1,-1,-1,-1]],[3],[5],[6],[7],[8]]
[null,true,true,true,false,false]
FindElements findElements = new FindElements([-1,-1,-1,-1,-1,-1,-1]);
findElements.find(3); // returns True
findElements.find(5); // returns True
findElements.find(6); // returns True
findElements.find(7); // returns False (no node with value 7 exists)
findElements.find(8); // returns False (no node with value 8 exists)
0
.x
, assign its left child 2 * x + 1
and right child 2 * x + 2
.set
or unordered_set
for quick lookup.O(1)
lookup in the find()
function.https://leetcode.com/problems/find-elements-in-a-contaminated-binary-tree/description/
Loading component...
Loading component...