Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var Queue = function() {
- this.array = [];
- this.count = 0;
- }
- Queue.prototype.enqueue = function(val){
- this.array.push(val);
- this.count++;
- }
- Queue.prototype.dequeue=function(){
- var temp = this.array.shift();
- this.count--;
- return temp;
- }
- Queue.prototype.size = function() {
- return this.count;
- }
- var Tree = function (val) {
- this.left= null;
- this.right=null;
- this.val=val;
- }
- Tree.prototype.addChild = function(val) {
- if (this.val > val) {
- if (this.left === null) {
- this.left= new Tree(val);
- } else {
- this.left.addChild(val);
- }
- }
- if (this.val < val) {
- if (this.right === null) {
- this.right= new Tree(val);
- } else {
- this.right.addChild(val);
- }
- }
- }
- // FIRST LEVEL STARTS AT LEVEL 1
- const findLargestLevel = function(node) {
- // your code here
- var arrayOfValues = [];
- var queued = new Queue;
- node.currentLevel = 0;
- queued.enqueue(node);
- var currentNode;
- var currentLevel = 0;
- while (queued.size() > 0) {
- currentNode = queued.dequeue();
- // keep track of the current level
- if (currentNode.currentLevel > currentLevel) {
- currentLevel++;
- }
- // adds val to current sum of vals at current level
- if (arrayOfValues[currentLevel] === undefined) {
- arrayOfValues[currentLevel] = currentNode.val;
- } else {
- arrayOfValues[currentLevel] += currentNode.val;
- }
- if (currentNode.left !== null) {
- currentNode.left.currentLevel = currentNode.currentLevel+1;
- queued.enqueue(currentNode.left);
- }
- if (currentNode.right !== null) {
- currentNode.right.currentLevel = currentNode.currentLevel+1;
- queued.enqueue(currentNode.right);
- }
- }
- console.log(arrayOfValues)
- return arrayOfValues.indexOf(Math.max(...arrayOfValues))+1;
- };
- // FIRST LEVEL STARTS AT LEVEL 1
- // var test = new Tree(0)
- // test.addChild(1)
- // test.addChild(-2)
- // test.addChild(6)
- // test.addChild(-1)
- // test.addChild(-4)
- // findLargestLevel(test)
- // // 0 . 0
- // // -2 1. 0
- // //-4-1 7 . 1
- // //
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement