Skip to content

Instantly share code, notes, and snippets.

@boxgames1
Created June 29, 2018 11:25
Show Gist options
  • Save boxgames1/bcc644ebf13b72546b8e160d3aa81958 to your computer and use it in GitHub Desktop.
Save boxgames1/bcc644ebf13b72546b8e160d3aa81958 to your computer and use it in GitHub Desktop.
BinaryTreeLevelorder
levelOrder() {
if (!this.root) return [];
var array = [];
search(this.root, 1, 1);
function search(node, level, index) {
if (node) {
const count = Math.pow(2, level - 1);
if (array.length < level) {
array.push(Array(count).fill(""));
}
var arr = array[level - 1];
arr[index - 1] = node;
const leftIndex = 2 * index - 1;
const rightIndex = 2 * index;
search(node.left, level + 1, leftIndex);
search(node.right, level + 1, rightIndex);
} else {
return;
}
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment