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

commented
var tree = {
    name: '**',
    children: [
        {
            name: '北京',
            children: [
                {
                    name: '朝阳群众'
                },
                {
                    name: '海淀区'
                },
                {
                    name: '昌平区'
                }
            ]
        },
        {
            name: '浙江省',
            children: [
                {
                    name: '杭州市',
                    code: '0571',
                },
                {
                    name: '嘉兴市'
                },
                {
                    name: '绍兴市'
                },
                {
                    name: '宁波市'
                }
            ]
        }
    ]
};


function fn(tree, name) {
    //bfs
    let Queue = [[tree.name, tree.children]];
    while (Queue.length > 0) {
        //出队当前节点
        let cur = Queue.shift();
        if (cur[0] === name) return { name: name, code: cur[1] }
        //将children入队
        if (cur.length === 1) continue;

        for (let node of cur[1]) {
            let obj = [node.name];
            if (node.hasOwnProperty("children")) obj.push(node.children);
            if (node.hasOwnProperty("code")) obj.push(node.code);
            Queue.push(obj);
        }
    }
    return -1;
}
var node = fn(tree, '杭州市');
console.log(node);    // { name: '杭州市', code: 0571 }

gettreenodeDeep(tree, name) {
const res = {}
const dfs = (tree, name) => {
if(!tree) {
return
}
if(tree.name === name) {
res.name = tree.name
res.code = tree.code
return
}
if(tree.children) {
for(let item of tree.children) {
dfs(item, name)
}
}

}

dfs(tree, name)

return res

}``

输入name,找code

function getCode(tree, cityName) {
  if (tree.name === cityName) {
    return tree.code || null;
  } else if (tree.children) {
    for (var i = 0; i < tree.children.length; i++) {
      var code = getCode(tree.children[i], cityName);
      if (code) {
        return code;
      }
    }
  }
  return null;
}
function getCode(tree, name) {
  let res = {}

  traversal(tree)
  return res

  function traversal(node) {
    if (!node) return

    if (node.name === name) {
      res = {...node}
      return
    }

    node.children && node.children.forEach(item => {
      traversal(item)
    })
  }
}

console.log(getCode(tree, '杭州市')) // { name: '杭州市', code: '0571' }