treeMap
Written on August 29, 2019
문제
Implement a map
method on this Tree class.
Map accepts a mapping function as its only argument. It traverses the tree, passing each node’s value into the mapping function, and generates a new tree containing the results.
So map
should return a tree with the same structure, and different values, but it should NOT modify the tree that was passed in.
Extra credit: Consider another method, mapInPlace
, which DOES modify the original tree instead of generating a new one. Why would you want to use this method instead of map
?
풀이
var Tree = function(value) {
this.value = value;
this.children = [];
};
Tree.prototype.map = function(callback) {
const retreiveTree = (node, newTree) => {
if (node.children.length === 0) {
return;
}
for (let i = 0; i < node.children.length; i++) {
let newChild = new Tree(callback(node.children[i].value));
newTree.children.push(newChild);
retreiveTree(node.children[i], newTree.children[i]);
}
};
let newTree = new Tree(callback(this.value));
retreiveTree(this, newTree);
return newTree;
};
Tree.prototype.mapInPlace = function(callback) {
const retreiveTree = node => {
node.value = callback(node.value);
if (node.children.length > 0) {
for (let i = 0; i < node.children.length; i++) {
retreiveTree(node.children[i]);
}
} else return;
};
retreiveTree(this);
return this;
};
👩🏻💻 배우는 것을 즐기는 프론트엔드 개발자 입니다
부족한 블로그에 방문해 주셔서 감사합니다 🙇🏻♀️
in the process of becoming the best version of myself