面试题之获取属性结构的所有叶子节点

实现一个函数,获取树形数据结构的所有叶子节点

在这里插入图片描述
代码如下:

<!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>

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值