js实现树形数据搜索
时间: 2023-12-09 09:03:09 浏览: 40
要实现树形数据搜索,可以使用深度优先搜索(DFS)或广度优先搜索(BFS)的算法。以下是使用DFS算法实现的js代码:
```javascript
function searchTree(node, query) {
if (!node) {
return null;
}
if (node.name === query) {
return node;
}
let result = null;
if (node.children) {
for (let i = 0; i < node.children.length; i++) {
result = searchTree(node.children[i], query);
if (result) {
break;
}
}
}
return result;
}
```
这个函数接收两个参数:要搜索的节点以及查询关键字。它首先检查当前节点是否与查询关键字匹配,如果匹配,就返回该节点。否则,它会递归遍历该节点的每个子节点,直到找到匹配的节点或搜索完整个树。如果找到匹配的节点,就返回该节点;否则返回 null。
使用方法如下:
```javascript
const tree = {
name: 'root',
children: [
{
name: 'child1',
children: [
{ name: 'grandchild1' },
{ name: 'grandchild2' },
],
},
{
name: 'child2',
children: [
{ name: 'grandchild3' },
{ name: 'grandchild4' },
],
},
],
};
const result = searchTree(tree, 'grandchild3');
console.log(result); // { name: 'grandchild3' }
```
这里我们定义了一棵树,然后调用 searchTree 函数来查找名为 'grandchild3' 的节点。函数会返回该节点的对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)