I am currently facing a challenge in identifying the leaf node within a non-binary tree that requires modification. The process involves computing a blake2b hash from the leaf data, passing it to the parent node, and repeating this calculation until reaching the root node where the same computation is performed.
The starting and end interfaces are outlined below:
interface sto {
name: string
children: sto[]
}
interface stoWithIds {
id: string // blake2b(data)
data: {
name: string
children: stoWithIds[]
}
}
The essential functions needed for this operation are as follows:
function transformSto (op: sto): stoWithIds {
const { children, ...rest } = op
return { id: '', data: { ...rest, children: [] } }
}
async function visitNode (node: sto, parent: stowithId) {
// This will begin execution when a leaf node is identified and progress upwards
node.children.map(async c => await visitNode(node, parent))
// Calculating the ids here
parent.children.push(/* our calculation, but this doesn't work for children on the same level*/)
}
The next step would be to invoke these functions:
const sto: sto = {
name: 'Root',
children: [
{
name: 'child 1',
children: [
{
name: 'child2',
children: []
},
{
name: 'child3',
children: []
}
]
}
]
}
await visitNode(sto, transformSto(sto))
The expected outcome after executing these operations should look like this:
const stowithId: stoWithIds = {
id: 'blake2b(data)',
data: {
name: 'Root',
children: [
{
id: 'blake2b(data)',
data: {
name: 'child 1',
children: [
{
id: 'blake2b(data)',
data: {
name: 'child2',
children: []
}
},
{
id: 'blake2b(data)',
data: {
name: 'child3',
children: []
}
}
]
}
}
]
}
}
I have been grappling with this issue for several hours now. While I believe there may be a straightforward solution, I am struggling to discover it. My knowledge of tree traversals is limited which has led me to dedicate most of my Sunday researching this topic without finding a resolution. Any assistance or guidance would be greatly appreciated.