Skip to content

Instantly share code, notes, and snippets.

@kcoyner
Created November 18, 2017 18:22
Show Gist options
  • Save kcoyner/9a906bcfcdb54cce1f3e5678fa652231 to your computer and use it in GitHub Desktop.
Save kcoyner/9a906bcfcdb54cce1f3e5678fa652231 to your computer and use it in GitHub Desktop.
whiteboard exercise: find largest level of a binary tree
You may use a whiteboard or paper to sketch things out, but please write your code in an IDE so you can write tests to demonstrate that your code works, and you can paste that code into a Github Gist upon solution submission.
You may only use the Internet to remind yourself of syntax (e.g., on the MDN site), not to look up anything specifically about this problem. Be reasonable -- stay within the bounds of what would be permissible in a live industry interview.
## Largest level of tree?
You are given a binary tree whose nodes all have integer values (both positive and negative).
Determine which level of the tree is the "largest", i.e., you sum all the node values at that level, and determine which level has the largest sum.
In the case of a tie, return the level closest to the root.
```
const findLargestLevel = function(node) {
var maxSum = node.value;
var sumLevel = 0;
var level = 0;
level++;
var nodeSum = node.children.reduce((accum, el) => {
accum += el.value;
return accum;
}, 0);
if (node.value > maxSum) {
maxSum = node.value;
sumLevel = level;
}
// traverse the tree horizontally
// recursion: check the value of the node, look at children, check their values
// for each that i traverse, i'll save the sum of the values and a row number
// on each level, compare that level's sum with the saved largest level to date
// if larger, assign the new larger number
// if equal, do nothing
// if smaller, do nothing
// return level number
};
```
var node = {value: 3, children: [ { value: 2, children: [ {value: 3, children: [] }, {value: 6, children: [] } ]} ] };
### Hints
Try not to use the hints if you can help it, but if you do want one, use [ROT-13](http://rot13.com/) to decode.
1. Erzrzore, yriry-beqre genirefny bs n gerr vf qbar jvgu oernqgu-svefg frnepu.
2. Oernqgu-svefg frnepu hfrf n urycre qngn fgehpgher: n dhrhr.
1. Remember, level-order traversal of a tree is done with breadth-first search.
2. Breadth-first search uses a helper data structure: a queue.
## When you are done
The *interviewee* should use the [submission form](https://docs.google.com/forms/d/e/1FAIpQLSci8YZr2L1HCBj-SiKASRHkeLfLHCl_TW4_17G72DTDJcuDZg/viewform) to submit a self-assessment.
The interviewer is not required to submit feedback, but is welcome to.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment