实现一个函数,获取树形数据结构的所有叶子节点
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
const input = [
{
name: 'A',
children: [
{
name: 'B',
children: [
{
name: 'D'
},
{
name: 'E'
}
]
},
{
name: 'C',
children: [
{
name: 'F'
}
]
}
]
}
]
function getTreeLeaf(data,output) {
for(let child of data) {
if(child.children){
getTreeLeaf(child.children,output)
}else{
output.push(child)
}
}
}
let arr = []
getTreeLeaf(input,arr)
console.log(arr)
</script>
</body>
</html>
优化后:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
const data = [
{
name: 'A',
children: [
{
name: 'B',
children: [
{
name: 'D'
},
{
name: 'E'
}
]
},
{
name: 'C',
children: [
{
name: 'F'
}
]
}
]
}
]
function getTreeLeaves(input) {
let arr = []//存储数据用于输出
for(let child of input) {//装逼用了for of进行数组遍历(for of遍历数组 for in遍历数组、对象 for of遍历对象需要配合Object.key())
if(child.children&&child.children.length) {//判断是否有分支以及分支是否为空
arr = arr.concat(getTreeLeaves(child.children)) //**重点:通过递归获得叶子节点(没有后续分支的节点)
}else{ //递归到还有分支的节点会再次执行函数递归直到找到叶子节点。
arr.push(child) //递归到叶子节点的分支会执行else的语句,把分支放到arr里,
} //通过return返回给上个递归的函数,上个函数通过concat把所有循环获得的数组组合
} //最上层的递归,即原函数会接收到组合而成的数组并输出
return arr
}
console.log(getTreeLeaves(data))
</script>
</body>
</html>