Skip to content

Instantly share code, notes, and snippets.

@adamaiken89
Created August 12, 2022 23:15
Show Gist options
  • Save adamaiken89/df1eb48e8504b6213a58f7477fef8acc to your computer and use it in GitHub Desktop.
Save adamaiken89/df1eb48e8504b6213a58f7477fef8acc to your computer and use it in GitHub Desktop.
Tree Transversal
interface TreeNode {
left: TreeNode | null;
right: TreeNode | null;
val: number;
};
function main(node: TreeNode) {
const list: string[] = [];
transversal('', node);
console.log(`The list is ${list}`);
const result = list.reduce( (total: number, value: string) => {
return total + Number(value);
}, 0);
console.log(`The result is ${result}`);
function transversal(valList: string, node: TreeNode) {
valList += node.val.toString();
if(node.left != null) {
transversal(valList, node.left);
}
if(node.right != null) {
transversal(valList, node.right);
}
if(node.left == null && node.right == null) {
list.push(valList);
}
}
}
const node: TreeNode = {
left: {
left: null,
right: null,
val: 17,
},
right: {
left: null,
right: null,
val: 9,
},
val: 12,
};
main(node);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment