Hello! I've been tasked with creating a function that iterates over a binary tree and returns all its values in pre-order. Here is the code snippet:
interface BinTree {
root: number;
left?: BinTree;
right?: BinTree;
};
const TreePreArray =(t:BinTree):number[] => {
let list = new Array<number>();
if (t == undefined) {return list }
else {
list.push(t.root)
list.concat(TreePreArray(t.left))
list.concat(TreePreArray(t.right))
}
return list
}
let bn : BinTree = {
root: 1,
left: { root: 2 },
right: { root: 3 }
}
console.log((TreePreArray(bn)));
However, the output only shows [1] instead of [1,2,3]. I found inspiration from this link Recursive Tree Traversal Method With Return Type Array and decided to implement it in TypeScript.