Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
Given a binary tree with the following rules:
root.val == 0treeNode:
treeNode.val has a value x and treeNode.left != null, then treeNode.left.val == 2 * x + 1treeNode.val has a value x and treeNode.right != null, then treeNode.right.val == 2 * x + 2Now 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) Returns true if the target value exists in the recovered binary tree.Example 1:
Input ["FindElements","find","find"] [[[-1,null,-1]],[1],[2]] Output [null,false,true] Explanation FindElements findElements = new FindElements([-1,null,-1]); findElements.find(1); // return False findElements.find(2); // return True
Example 2:
Input ["FindElements","find","find","find"] [[[-1,-1,-1,-1,-1]],[1],[3],[5]] Output [null,true,true,false] Explanation FindElements findElements = new FindElements([-1,-1,-1,-1,-1]); findElements.find(1); // return True findElements.find(3); // return True findElements.find(5); // return False
Example 3:
Input ["FindElements","find","find","find","find"] [[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]] Output [null,true,false,false,true] Explanation FindElements findElements = new FindElements([-1,null,-1,-1,null,-1]); findElements.find(2); // return True findElements.find(3); // return False findElements.find(4); // return False findElements.find(5); // return True
Constraints:
TreeNode.val == -120[1, 104]find() is between [1, 104]0 <= target <= 106Problem summary: Given a binary tree with the following rules: root.val == 0 For any treeNode: If treeNode.val has a value x and treeNode.left != null, then treeNode.left.val == 2 * x + 1 If treeNode.val has a value x and treeNode.right != null, then treeNode.right.val == 2 * x + 2 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) Returns true if the target value exists in the recovered binary tree.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Tree · Design
["FindElements","find","find"] [[[-1,null,-1]],[1],[2]]
["FindElements","find","find","find"] [[[-1,-1,-1,-1,-1]],[1],[3],[5]]
["FindElements","find","find","find","find"] [[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1261: Find Elements in a Contaminated Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class FindElements {
private Set<Integer> s = new HashSet<>();
public FindElements(TreeNode root) {
root.val = 0;
dfs(root);
}
public boolean find(int target) {
return s.contains(target);
}
private void dfs(TreeNode root) {
s.add(root.val);
if (root.left != null) {
root.left.val = root.val * 2 + 1;
dfs(root.left);
}
if (root.right != null) {
root.right.val = root.val * 2 + 2;
dfs(root.right);
}
}
}
/**
* Your FindElements object will be instantiated and called as such:
* FindElements obj = new FindElements(root);
* boolean param_1 = obj.find(target);
*/
// Accepted solution for LeetCode #1261: Find Elements in a Contaminated Binary Tree
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type FindElements struct {
s map[int]bool
}
func Constructor(root *TreeNode) FindElements {
root.Val = 0
s := map[int]bool{}
var dfs func(*TreeNode)
dfs = func(root *TreeNode) {
s[root.Val] = true
if root.Left != nil {
root.Left.Val = root.Val*2 + 1
dfs(root.Left)
}
if root.Right != nil {
root.Right.Val = root.Val*2 + 2
dfs(root.Right)
}
}
dfs(root)
return FindElements{s}
}
func (this *FindElements) Find(target int) bool {
return this.s[target]
}
/**
* Your FindElements object will be instantiated and called as such:
* obj := Constructor(root);
* param_1 := obj.Find(target);
*/
# Accepted solution for LeetCode #1261: Find Elements in a Contaminated Binary Tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class FindElements:
def __init__(self, root: Optional[TreeNode]):
def dfs(root: Optional[TreeNode]):
self.s.add(root.val)
if root.left:
root.left.val = root.val * 2 + 1
dfs(root.left)
if root.right:
root.right.val = root.val * 2 + 2
dfs(root.right)
root.val = 0
self.s = set()
dfs(root)
def find(self, target: int) -> bool:
return target in self.s
# Your FindElements object will be instantiated and called as such:
# obj = FindElements(root)
# param_1 = obj.find(target)
// Accepted solution for LeetCode #1261: Find Elements in a Contaminated Binary Tree
use rustgym_util::*;
use std::collections::HashSet;
trait Preorder {
fn recover(&mut self, x: i32, hs: &mut HashSet<i32>);
}
impl Preorder for TreeLink {
fn recover(&mut self, x: i32, hs: &mut HashSet<i32>) {
if let Some(node) = self {
hs.insert(x);
node.borrow_mut().val = x;
node.borrow_mut().left.recover(2 * x + 1, hs);
node.borrow_mut().right.recover(2 * x + 2, hs);
}
}
}
struct FindElements {
root: TreeLink,
hs: HashSet<i32>,
}
impl FindElements {
fn new(mut root: TreeLink) -> Self {
let mut hs = HashSet::new();
root.recover(0, &mut hs);
FindElements { root, hs }
}
fn find(&self, target: i32) -> bool {
self.hs.contains(&target)
}
}
#[test]
fn test() {
let root = tree!(-1, None, tree!(-1));
let fe = FindElements::new(root);
let target = 1;
let res = false;
assert_eq!(fe.find(target), res);
let target = 2;
let res = true;
assert_eq!(fe.find(target), res);
let root = tree!(-1, tree!(-1, tree!(-1), tree!(-1)), tree!(-1));
let fe = FindElements::new(root);
let target = 1;
let res = true;
assert_eq!(fe.find(target), res);
let target = 3;
let res = true;
assert_eq!(fe.find(target), res);
let target = 5;
let res = false;
assert_eq!(fe.find(target), res);
let root = tree!(-1, None, tree!(-1, tree!(-1, tree!(-1), None), None));
let fe = FindElements::new(root);
let target = 2;
let res = true;
assert_eq!(fe.find(target), res);
let target = 3;
let res = false;
assert_eq!(fe.find(target), res);
let target = 4;
let res = false;
assert_eq!(fe.find(target), res);
let target = 5;
let res = true;
assert_eq!(fe.find(target), res);
}
// Accepted solution for LeetCode #1261: Find Elements in a Contaminated Binary Tree
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
class FindElements {
readonly #s = new Set<number>();
constructor(root: TreeNode | null) {
root.val = 0;
const dfs = (node: TreeNode | null, x = 0) => {
if (!node) return;
this.#s.add(x);
dfs(node.left, x * 2 + 1);
dfs(node.right, x * 2 + 2);
};
dfs(root);
}
find(target: number): boolean {
return this.#s.has(target);
}
}
/**
* Your FindElements object will be instantiated and called as such:
* var obj = new FindElements(root)
* var param_1 = obj.find(target)
*/
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.