Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //OICE
- //I: Binary tree: array of objects with a value, length and children property.
- //O: The level which has the largest summed value;
- //C: -
- //E: -
- //We are going to create a modified version of the binary tree that should expedite this process for us.
- //We each level, we will also have a level property on the node that will allow us to eval deeply nested
- //But far separated nodes on the same level.
- const ModBinaryTree = (value, level = 0) => {
- this.value = value;
- this.level = level;
- this.children = [];
- };
- //This would be a very straight forward addition to a binary tree as you could just base the next recursive call's
- //level children's level value +1 on the current.
- //Then we can find the sum of each level
- const findLargestLevel = (tree) => {
- let levelSumObj = {};
- let largest = [0,0];
- (function walkThatTree(arrOfNodes) {
- if (arrOfNodes !== undefined) {
- let sumNode = arrOfNodes.reduce((total, ele) => {
- total += ele.value;
- walkThatTree(ele.children);
- return total;
- }, 0);
- if (levelSumObj[arrOfNodes[0].level]) levelSumObj[arrOfNodes[0].level] += sumNode;
- else levelSumObj[arrOfNodes[0].level] = sumNode;
- }
- }(tree));
- for (let keys in levelSumObj) {
- if (levelSumObj[keys] > largest[1]) {
- largest[0] = keys;
- largest[1] = levelSumObj[keys]
- }
- }
- return largest[0];
Add Comment
Please, Sign In to add comment