Skip to content

Instantly share code, notes, and snippets.

@sansarun
Created May 17, 2023 09:45
Show Gist options
  • Save sansarun/b60d20714f09c0d752554fc460e6de81 to your computer and use it in GitHub Desktop.
Save sansarun/b60d20714f09c0d752554fc460e6de81 to your computer and use it in GitHub Desktop.
function getLeafNodes(data) {
const leafNodes = [];
function traverse(node) {
if (node.children.length === 0) {
leafNodes.push(node.name);
} else {
for (let i = 0; i < node.children.length; i++) {
traverse(node.children[i]);
}
}
}
traverse(data);
return leafNodes;
}
// Unit tests
// Test case 1: Basic example
const input1 = {
name: "A",
children: [
{
name: "B",
children: [
{
name: "C",
children: [],
},
],
},
{
name: "D",
children: [],
},
],
};
const expectedOutput1 = ["C", "D"];
const actualOutput1 = getLeafNodes(input1);
console.log(JSON.stringify(actualOutput1) === JSON.stringify(expectedOutput1)); // Output: true
// Test case 2: Tree with multiple levels of leaf nodes
const input2 = {
name: "A",
children: [
{
name: "B",
children: [
{
name: "C",
children: [],
},
{
name: "D",
children: [],
},
],
},
{
name: "E",
children: [
{
name: "F",
children: [],
},
{
name: "G",
children: [],
},
],
},
],
};
const expectedOutput2 = ["C", "D", "F", "G"];
const actualOutput2 = getLeafNodes(input2);
console.log(JSON.stringify(actualOutput2) === JSON.stringify(expectedOutput2)); // Output: true
// Test case 3: Tree with a single leaf node
const input3 = {
name: "A",
children: [
{
name: "B",
children: [],
},
],
};
const expectedOutput3 = ["B"];
const actualOutput3 = getLeafNodes(input3);
console.log(JSON.stringify(actualOutput3) === JSON.stringify(expectedOutput3)); // Output: true
// Test case 4: Tree with no leaf nodes
const input4 = {
name: "A",
children: [],
};
const expectedOutput4 = ["A"];
const actualOutput4 = getLeafNodes(input4);
console.log(JSON.stringify(actualOutput4) === JSON.stringify(expectedOutput4)); // Output: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment