Problem
Given a binary tree with the following rules:
root.val == 0
- For any
treeNode
:- If
treeNode.val
has a valuex
andtreeNode.left != null
, thentreeNode.left.val == 2 * x + 1
- If
treeNode.val
has a valuex
andtreeNode.right != null
, thentreeNode.right.val == 2 * x + 2
- If
Now the binary tree is contaminated, which means all treeNode.val
have been changed to -1
.
Implement the FindElements
class:
FindElements(TreeNode* root)
Initializes the object with a contaminated binary tree and recovers it.bool find(int target)
Returnstrue
if thetarget
value exists in the recovered binary tree.
Examples
Example 1:
graph LR subgraph Original A1(("-1")) B1:::hidden C1(("-1")) A1 ~~~ B1 A1 --> C1 end subgraph After["Recovered"] A2((0)) B2:::hidden C2((2)) A2 ~~~ B2 A2 --> C2 end Original --> After classDef hidden display: none;
|
|
Example 2:
graph LR subgraph Original A1(("-1")) B1(("-1")) C1(("-1")) D1(("-1")) E1(("-1")) A1 --> B1 & C1 B1 --> D1 & E1 end subgraph After["Recovered"] A2((0)) B2((1)) C2((2)) D2((3)) E2((4)) A2 --> B2 & C2 B2 --> D2 & E2 end Original --> After
|
|
Example 3:
graph LR subgraph Original A1(("-1")) B1:::hidden C1(("-1")) D1(("-1")) E1 F1(("-1")) G1 A1 ~~~ B1 A1 --> C1 C1 --> D1 C1 ~~~ E1:::hidden D1 --> F1 D1 ~~~ G1:::hidden end subgraph After["Recovered"] A2((0)) B2:::hidden C2((2)) D2(("5")) E2 F2(("11")) G2 A2 ~~~ B2 A2 --> C2 C2 --> D2 C2 ~~~ E2:::hidden D2 --> F2 D2 ~~~ G2:::hidden end Original --> After classDef hidden display: none;
|
|
Constraints:
TreeNode.val == -1
- The height of the binary tree is less than or equal to
20
- The total number of nodes is between
[1, 10^4]
- Total calls of
find()
is between[1, 10^4]
0 <= target <= 10^6
Solution
The problem requires us to reconstruct the original values of a contaminated binary tree, where every node initially had a specific value following certain rules. All node values of the tree are replaced by -1
, and we need to:
- Recover the Tree Values: Based on the rules of node recovery:
- If a node
x
has a left child, the left child value is given by2 * x + 1
. - If a node
x
has a right child, the right child value is2 * x + 2
. - The root has a value
0
.
- If a node
- Find Target in the Recovered Tree: To check if a target value exists in the recovered tree.
Method 1 - DFS
Here is how we will solve it:
- Recover the Tree:
- Use a recursive DFS starting from the root. Set the root’s value to
0
and propagate the rules for its left and right nodes.
- Use a recursive DFS starting from the root. Set the root’s value to
- Find Method:
- Use a
HashSet
(or equivalent) to store all the recovered node values forO(1)
retrieval.
- Use a
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
- Recover:
O(n)
(wheren
is the number of nodes). - Find: O(1) as it uses hashset
- Recover:
- 🧺 Space complexity:
O(n)
due to the hash set storing node values + recursion stack in DFS