Skip to content

Instantly share code, notes, and snippets.

@blacksheep557
Created May 18, 2020 15:27
Show Gist options
  • Select an option

  • Save blacksheep557/27aafc6776c936bcf1cf9d2ad91a8e81 to your computer and use it in GitHub Desktop.

Select an option

Save blacksheep557/27aafc6776c936bcf1cf9d2ad91a8e81 to your computer and use it in GitHub Desktop.
function treeToArray(tree) {
let result = [tree['value']];
let pointer = 0;
while (pointer < result.length) {
if (result[pointer] !== null) {
while (result[result.length - 1] === null) {
result.pop()
}
let children = findNode(tree, result[pointer]);
if(pointer>=result.length){
break;
}
result.push(...children);
}
pointer++;
}
while (result[result.length - 1] === null) {
result.pop()
}
console.log(result);
return result
}
function findNode(root, target) {
if (root.value === target) {
return [root.left !== undefined ? root.left.value : null, root.right !== undefined ? root.right.value : null]
} else {
if (root.left !== undefined) {
if (findNode(root.left, target) !== undefined) {
return findNode(root.left, target);
}
}
if (root.right !== undefined) {
if (findNode(root.right, target) !== undefined) {
return findNode(root.right, target);
}
}
}
return undefined;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment