Created
June 29, 2018 11:25
-
-
Save boxgames1/bcc644ebf13b72546b8e160d3aa81958 to your computer and use it in GitHub Desktop.
BinaryTreeLevelorder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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