We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
法一:
function bfs(target, id) { const quene = [...target] do { const current = quene.shift() if (current.children) { quene.push(...current.children.map(x => ({ ...x, path: (current.path || current.id) + '-' + x.id }))) } if (current.id === id) { return current } } while(quene.length) return undefined } function dfs(target, id) { const stask = [...target] do { const current = stask.pop() if (current.children) { stask.push(...current.children.map(x => ({ ...x, path: (current.path || current.id) + '-' + x.id }))) } if (current.id === id) { return current } } while(stask.length) return undefined } // 公共的搜索方法,默认bfs function commonSearch(target, id, mode) { const staskOrQuene = [...target] do { const current = staskOrQuene[mode === 'dfs' ? 'pop' : 'shift']() if (current.children) { staskOrQuene.push(...current.children.map(x => ({ ...x, path: (current.path || current.id) + '-' + x.id }))) } if (current.id === id) { return current } } while(staskOrQuene.length) return undefined }
法二:
let list = [{ id: '1', children: [{ id: '11', children: [{ id: '111' }, { id: '112' }] }] }]; function fn(value) { // 回溯的标记 let _p = Symbol('parent'); // 找到子节点 let result; function _fn(arr, p) { for (let i = 0; i < arr.length; i++) { arr[i][_p] = p; if (arr[i].id === value) { result = arr[i]; return; } !result && arr[i].children && _fn(arr[i].children, arr[i]) } if (result) return; } _fn(list, null); let tmp = []; if (!result) return null; while (result) { tmp.unshift(result.id); result = result[_p]; } return tmp; }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
法一:
刚刚好,中间仅仅差了一个数组方法:
法二:
The text was updated successfully, but these errors were encountered: