深度优先搜索树节点
约 103 字小于 1 分钟
2025-01-21
interface TreeNode {
[key: string]: any;
}
/**
* 深度优先搜索树节点
* @param tree 要查找的树
* @param targetValue 要查找的值
* @param key 值对应的key
* @returns tree
*/
export function dfsSearchTree<T extends TreeNode>(tree: T[], targetValue: any, key: string = 'value'): TreeNode | null {
for (let node of tree) {
if (node[key] === targetValue) {
const { children, ...nodeWithoutChildren } = node;
return nodeWithoutChildren;
}
if (node.children && node.children.length > 0) {
const result = dfsSearchTree(node.children, targetValue, key);
if (result) {
return result;
}
}
}
return null;
}