Skip to content
New issue

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

对象树遍历 #42

Open
Sunny-117 opened this issue Nov 3, 2022 · 2 comments
Open

对象树遍历 #42

Sunny-117 opened this issue Nov 3, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

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));
@kangkang123269
Copy link

kangkang123269 commented Feb 23, 2023

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']

@lesenelir
Copy link

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))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants