Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

对象树遍历

Sunny-117 opened this issue · comments

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