根据id找节点

场景:给出一个节点树,根据id找出对应的节点
节点树:

let tree = {
	id: 1,
	children: [
		{
			id: 2,
			children: [
				{id: 3},
				{
					id: 5,
					children: [
						{id: 6}
					]
				},
				null
			]
		},
		{
			id: 4
		},
		null
	]
}

// 写一个方法
function getNode(root, id) {
// 方法
}

console.log('1===>', getNode(tree, 1))
console.log('2===>', getNode(tree, 2))
console.log('3===>', getNode(tree, 3))
console.log('4===>', getNode(tree, 4))
console.log('5===>', getNode(tree, 5))
console.log('6===>', getNode(tree, 6))
console.log('10===>', getNode(tree, 10))

思路一:根据把它变成数组,然后用数组的思维去遍历数组找出对应的节点

function getNode(root, id) {
	let arr = [root]
	let res = null
	while(arr.length){
		let o = arr.pop()
		if(o && o.id == id){
			res = o
			break
		} else if(o && o.children && o.children.length ) {
			arr.push(...o.children)
		}
	}
	return res
}

思路二:利用递归的思路:

function getNode(root, id) {
	let resultNode = null;
	findNode(root, id);
	function findNode(root, id){
		if(!!root) {
			let type = Object.prototype.toString.call(root);
			if(type === '[object Object]') {
				if(root.id && root.id === id) {
					resultNode = root
				} else {
					let node = root.children || null
					findNode(node, id);
				}
			}else if(type === '[object Array]') {
				let needNode = root.find(i=> !!i === true && i.id === id);
				if(!!needNode) {
					resultNode = needNode;
				} else {
					if(root.length) {
						root.forEach(item=>{
							if(item && item.children) {
								let node = item.children
								if(node && node.length){
									findNode(node, id);
								}
							}
						})
					}
				}
			}
		}
	}
	return resultNode;
}

综合来讲: 第一种方式会比较好些,代码简洁,性能也比较高。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值