This is a new series where I document my struggles of leetcode questions hoping seeing however small of an audience I get gives me the motivation to continue.
This problem is relatively simple, but a small trick can speed up the performance well. I believe if you know how to do BFS to traverse the tree then you should have no problem adding values to the tree.
Below is my code:
var FindElements = function(root) {
root.val = 0;
const stack = [root];
let current;
const record = new Set();
while (stack.length) {
current = stack.shift();
record.add(current.val);
if (current.left) {
current.left.val = getLeft(current.val);
stack.push(current.left);
}
if (current.right) {
current.right.val = getRight(current.val);
stack.push(current.right);
}
}
this.record = record;
function getLeft (num) { return 2 * num + 1; }
function getRight (num) { return 2 * num + 2; }
};
FindElements.prototype.find = function(target) {
return this.record.has(target);
};
I did not think of using a set for my answer, this was suggested by a better performance solution. Pretty neat, might come in handy one day for me.
Let me know anything on your mind after reading through this, THANKS!
Top comments (0)