Created
May 17, 2023 09:45
-
-
Save sansarun/b60d20714f09c0d752554fc460e6de81 to your computer and use it in GitHub Desktop.
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
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