Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
}
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;
}
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