Created
June 11, 2022 22:27
-
-
Save crutchcorn/c82911fe51cefea6db2037c096f6102d to your computer and use it in GitHub Desktop.
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
function treeByLevels (rootNode) { | |
let sortedArr = [] | |
if (!rootNode) return sortedArr; | |
sortedArr.push(rootNode.value); | |
let toReadAfter = []; | |
currNode = rootNode; | |
while (currNode) { | |
currNode.left && sortedArr.push(currNode.left.value); | |
currNode.right && sortedArr.push(currNode.right.value); | |
if (currNode.left) toReadAfter.push(currNode.left); | |
if (currNode.right) toReadAfter.push(currNode.right); | |
currNode = toReadAfter.shift() | |
} | |
return sortedArr; | |
} |
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
function treeByLevels (rootNode, sortedArr = []) { | |
if (!rootNode) return [] | |
sortedArr.push(rootNode.value); | |
rootNode.left && treeByLevels(rootNode.left, sortedArr); | |
rootNode.right && treeByLevels(rootNode.right, sortedArr); | |
return sortedArr; | |
} |
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
class Node { | |
constructor(value, left = null, right = null) { | |
this.value = value; | |
this.left = left; | |
this.right = right; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment