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
const tree = { name: 'root', children: [ { name: 'c1', children: [ { name: 'c11', children: [] }, { name: 'c12', children: [] } ] }, { name: 'c2', children: [ { name: 'c21', children: [] }, { name: 'c22', children: [] } ] } ] } // 深度优先的方式遍历 打印 name // ['root', 'c1','c11', 'c12', 'c2', 'c21', 'c22'] // 我写的 function solve(root) { const res = [] function dfs(root) { for (const key in root) { if (key === 'name') { res.push(root[key]) } else if (key === 'children') { root[key].forEach(ele => { dfs(ele) }); } } } dfs(root) return res; } console.log(solve(tree));
The text was updated successfully, but these errors were encountered:
function dfs(node, result) { result.push(node.name); // 先将当前节点的 name 加入到结果数组中 if (node.children) { for (const child of node.children) { dfs(child, result); // 对每个子节点进行递归遍历 } } } const result = []; dfs(tree, result); console.log(result); // ['root', 'c1', 'c11', 'c12', 'c2', 'c21', 'c22']
Sorry, something went wrong.
function getName(tree) { let res = [] traversal(tree) return res function traversal(node) { if (!node) return res.push(node.name) node.children && node.children.forEach(item => { traversal(item) }) } } console.log(getName(tree))
No branches or pull requests
The text was updated successfully, but these errors were encountered: