Created
August 12, 2022 23:15
-
-
Save adamaiken89/df1eb48e8504b6213a58f7477fef8acc to your computer and use it in GitHub Desktop.
Tree Transversal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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