JSFiddle - React, Tailwind, and code Playground
JavaScript
const tree = {
value: 1,
next: [
{
value: 4,
next: [
{
value: 5,
next: []
},
{
value: 3,
next: [
{
value: 6,
next: []
}
]
}
]
},
{
value: 10,
next: []
}
]
};
const sumAllValue = (tree) => {
let result = 0;
const DFS = (tree) => {
result += tree.value;
if (tree.next.length) {
tree.next.forEach((child) => {
DFS(child)
});
}
};
DFS(tree);
return result
};
alert(sumAllValue(tree));