【面试题集—No.08】过滤树的问题-深信服2021秋招

博客介绍了如何过滤掉一个树形结构中不含特定filtername的节点。通过从上至下或从下至上的遍历策略,判断节点是否包含目标名称,并将其添加到新的树结构中。博主分享了理解题目和代码的过程,强调深入理解与避免浅尝辄止的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

过滤掉一个树形结构中不含给定的 filtername 的结点
eg例子🌰:[{name: 'A', children: [ {name: 'B'} ]},{name: 'C'}]filtername='B' 过滤后则成为 [{name: 'A', children: [ {name: 'B'} ]}]

原理:

//原理:
function fn(a){
    if(a>3) return
    console.log(a);
    b=a+1;
    fn(b);
    console.log(a)
}
fn(1)    // 1 2 3 3 2 1

实现思路:

1. 从上至下:使用 forEach() 对tree进行遍历,使用 if hasOwnProperty('children') deep+1 得到tree的深度
2. 从下至上:!hasOwnProperty('children') 后,判断是否 == 目标结点
    1. 如果 !=,什么都不做,继续向上走
    2. 如果 ==,准备把该node加入到new_tree中
        1. node 需作为 child-node1
        2. 先放入 temp_tree 中
        3. 当

代码:

let new_tree = []

function filter(tree, str, deep) {
    let temp_tree = []
    tree.forEach(node => {
        if (!node.hasOwnProperty('children')) {
            if (deep === 1 && node['name'] === str) {
                new_tree.push(node)     //第一层满足,直接推入new_tree即可
            } else if (node['name'] === str) {
                temp_tree.push(node)
            }
        } else {
            let temp = deep + 1
            let bl = filter(node['children'], str, temp)
            if (bl.length != 0) {       //对象长度 = 树的深度,此处用来判断2-1
                node['children'] = bl   //2-2-1,返回的temp_node拿child包一下
                temp_tree.push(node)
                if (deep === 1) {
                    new_tree.push(node) 
                }
            }
        }
    })
    return temp_tree
}

举个例子🌰:

var tree = [
    { name: 'a' },
    {
        name: 'b',
        children: [
            { name: 'a' },
            {
                name: 'b1',
                children: [
                    { name: 'a' },
                    {
                        name: 'xxx',
                        children: [
                            { name: 'a' }
                        ]
                    }
                ]
            }
        ]
    },
    {
        name: 'c',
        children: [
            { name: 'b' },
            { name: 'b1' }
        ]
    }
]
console.log(JSON.stringify(tree))
filter(tree, 'a', 1)
console.log(JSON.stringify(new_tree))

运行结果: 

// [{"name":"a"},{"name":"b","children":[{"name":"a"},{"name":"b1","children":[{"name":"a"},{"name":"b2","children":[{"name":"a"}]}]}]},{"name":"c","children":[{"name":"c1"},{"name":"c2"}]}]
// [{"name":"a"},{"name":"b","children":[{"name":"a"},{"name":"b1","children":[{"name":"a"},{"name":"b2","children":[{"name":"a"}]}]}]}]

 

废话篓子🗑:

我哥自己写出来的,我花一下午看着他写好的代码才琢磨出来,而且一开始还没读懂题。和大佬的差距好像不是一星半点😭。我哥还说这题不配他写博客,属实是我这菜狗不配了。

还有要保证自己的每一篇文章都是彻底理解而不是浮在表面,这个就需要自己不断完善了。还有别整理完就又忘记了,拒绝暂时懂了❌!就像收藏夹不是用来积灰的,博客也不是用来包豆子的。(为了改掉这个坏习惯,后来大多数时候我都是看过才会给它塞收藏夹里。)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值