My task was to create a function that traverses a binary tree and returns an array of all its values in inorder. The code provided is:
interface BinTree {
root: number;
left?: BinTree;
right?: BinTree;
};
const TreeInArray =(t:BinTree):number[] =>{
let list = new Array<number>();
if (t.left!=undefined) {
list = list.concat(TreePreArray(t.left))
}
list.push(t.root)
if (t.right!=undefined){
list = list.concat(TreePreArray(t.right))
}
return list
}
let bn1 : BinTree = { // DOES NOT PASS TYPE CHECKING
root: 1,
left: { root: 2 ,
left:{root:4 },right:{root:5 } },
right: { root: 3}
}
console.log((TreeInArray(bn1)));
The current output is
[ 2, 4, 5, 1, 3 ]
However, I was hoping for an output like this
[4, 2, 5, 1, 3]
I'm trying to understand why the output differs from my expectations. Any insights?