树形结构根据节点查找某条路径(typescript)

这是节点结构,默认name在数组当中的所有对象中具有唯一性。当然,如果需要,可以添加利用唯一id当作标识。

interface DataFormat {
    name:string,
    children?:Array<DataFormat>
}

我写了一个用于遍历的数组结构和一个目标节点。testData从name为0的根节点开始开始,深度增加,每一个叶子节点都有name属性,并且可能存在children属性,children是数组结构,若存在children结构,则说明当前节点存在子节点。

const testData:DataFormat={
    name:'0',
    children:[{
        name:'1',
        children:[{
            name:'11'
        },{
            name:'12'
        }]
    },{
    name:'2'
},{
    name:'3',
        children:[{
        name:'31',
        children:[{
            name:'311',
        },{
            name:'312',
            children:[{
                name:'3112',
            }]
        }]
    },{
        name:'32'
    }]
}]
}

const node:DataFormat={name:'32'};

为了在最后能够保存得到的路径,我创建了一个

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个使用 TypeScript 实现的树结构数据递归函数的示例: ```typescript interface TreeNode<T> { value: T; children: TreeNode<T>[]; } function traverseTree<T>(node: TreeNode<T>, callback: (value: T) => void) { callback(node.value); node.children.forEach(child => { traverseTree(child, callback); }); } ``` 上述代码定义了一个 `TreeNode` 接口,表示树节点结构,包含一个值和子节点数组。然后,`traverseTree` 函数接受一个树节点和一个回调函数作为参数,用于遍历树并对每个节点的值执行回调函数。 通过递归调用 `traverseTree` 函数,它会首先执行当前节点的回调函数,然后递归地遍历每个子节点,并依次执行它们的回调函数。 以下是使用示例: ```typescript interface Person { name: string; } const tree: TreeNode<Person> = { value: { name: "Alice" }, children: [ { value: { name: "Bob" }, children: [ { value: { name: "Charlie" }, children: [] } ] }, { value: { name: "David" }, children: [] } ] }; function printName(person: Person) { console.log(person.name); } traverseTree(tree, printName); ``` 在上述示例中,我们定义了一个树结构的数据 `tree`,其中每个节点都包含一个 `name` 属性。然后,我们定义了一个打印姓名的回调函数 `printName`。 最后,我们调用 `traverseTree` 函数,传入树结构数据和回调函数,它会按照深度优先的顺序遍历树,并打印每个节点的姓名。 注意:这只是一个简单的示例,您可以根据实际需求扩展和修改代码来适应不同的树结构和操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值