|
| 1 | +/** |
| 2 | + * 1261. Find Elements in a Contaminated Binary Tree |
| 3 | + * https://leetcode.com/problems/find-elements-in-a-contaminated-binary-tree/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given a binary tree with the following rules: |
| 7 | + * 1. root.val == 0 |
| 8 | + * 2. For any treeNode: |
| 9 | + * 1. If treeNode.val has a value x and treeNode.left != null, |
| 10 | + * then treeNode.left.val == 2 * x + 1 |
| 11 | + * 2. If treeNode.val has a value x and treeNode.right != null, |
| 12 | + * then treeNode.right.val == 2 * x + 2 |
| 13 | + * |
| 14 | + * Now the binary tree is contaminated, which means all treeNode.val have |
| 15 | + * been changed to -1. |
| 16 | + * |
| 17 | + * Implement the FindElements class: |
| 18 | + * - FindElements(TreeNode* root) Initializes the object with a contaminated binary |
| 19 | + * tree and recovers it. |
| 20 | + * - bool find(int target) Returns true if the target value exists in the recovered |
| 21 | + * binary tree. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * Definition for a binary tree node. |
| 26 | + * function TreeNode(val, left, right) { |
| 27 | + * this.val = (val===undefined ? 0 : val) |
| 28 | + * this.left = (left===undefined ? null : left) |
| 29 | + * this.right = (right===undefined ? null : right) |
| 30 | + * } |
| 31 | + */ |
| 32 | +/** |
| 33 | + * @param {TreeNode} root |
| 34 | + */ |
| 35 | +var FindElements = function(root) { |
| 36 | + this.values = new Set(); |
| 37 | + root.val = 0; |
| 38 | + |
| 39 | + const traverse = node => { |
| 40 | + if (!node) return; |
| 41 | + this.values.add(node.val); |
| 42 | + if (node.left) node.left.val = 2 * node.val + 1; |
| 43 | + if (node.right) node.right.val = 2 * node.val + 2; |
| 44 | + traverse(node.left); |
| 45 | + traverse(node.right); |
| 46 | + }; |
| 47 | + |
| 48 | + traverse(root); |
| 49 | +}; |
| 50 | + |
| 51 | +/** |
| 52 | + * @param {number} target |
| 53 | + * @return {boolean} |
| 54 | + */ |
| 55 | +FindElements.prototype.find = function(target) { |
| 56 | + return this.values.has(target); |
| 57 | +}; |
0 commit comments