LeetCode 1261: Find Elements in a Contaminated Binary Tree

Problem Description

Explanation:

  • We are given a contaminated binary tree where each node's value has been changed to -1.
  • The original binary tree followed a specific rule for values: root.val = 0, left child's value = 2 * parent's value + 1, right child's value = 2 * parent's value + 2.
  • We need to implement a class that can recover the original binary tree and check if a given value exists in the recovered tree.

Algorithm:

  1. Initialize the root with value 0, and recursively recover the left and right subtrees.
  2. Use a set to store all values in the recovered tree.
  3. For the find function, simply check if the target value exists in the set.

Time Complexity:

  • Initialization: O(n) where n is the number of nodes
  • Finding: O(1)

Space Complexity:

  • Initialization: O(n) where n is the number of nodes
  • Finding: O(1)

:

Solutions

import java.util.HashSet;
import java.util.Set;

class FindElements {
    private Set<Integer> values;

    public FindElements(TreeNode root) {
        values = new HashSet<>();
        recover(root, 0);
    }

    private void recover(TreeNode node, int val) {
        if (node == null) return;
        node.val = val;
        values.add(val);
        recover(node.left, 2 * val + 1);
        recover(node.right, 2 * val + 2);
    }

    public boolean find(int target) {
        return values.contains(target);
    }
}

Loading editor...