# 问一个tree数据结构向上取值的问题？

...

``````const arr = [
{
code:'12',
name:'中国',
type:0,
children:[{
code:'23',
name:'江苏',
type:1,
children:[{
code:'34',
name:'苏州',
type:2,
children:[{
code:'45',
name:'工业园区',
type:3
}]
}]
}]
}
]``````

4 个回答
``````const getCode = ([{code, children}], val, codeList = []) => codeList.push(code) && (code !== val ? getCode(children, val, codeList) : codeList)
console.log(getCode(arr, '45'))``````
``````function getCodes(code, arr) {
let res = null
function dps(nodes, codes) {
if (!nodes) return

for (let i = 0; i < nodes.length; i++) {
if (res) return
const node = nodes[i]
if (node.code === code) {
res = [...codes, node.code]
return
}
dps(node.children, [...codes, node.code])
}
}
dps(arr, [])
return res
}
console.log(getCodes('45', arr))``````

``````function getCodes(code, arr) {
function dps(nodes, codes) {
if (!nodes) return

for (let i = 0; i < nodes.length; i++) {
const node = nodes[i]
codes.push(node.code)

if (node.code === code) return codes
const res = dps(node.children, codes)
if (res) return res

codes.pop()
}
}
return dps(arr, [])
}``````

``````const arr = [
{
code: '12',
name: '中国',
type: 0,
children: [
{
code: '23',
name: '江苏',
type: 1,
children: [
{
code: '34',
name: '苏州',
type: 2,
children:[
{
code: '45',
name: '工业园区',
type: 3
}
]
},
{
code: "35",
children: [
{
code: "46"
}
]
}
]
}
]
}
];

function queryCodeArray(code, list) {
for (let item of list) {
const codes = [];
if (item.code === code) {
codes.push(item.code);
return codes;
}
if (item.children) {
codes.push(item.code);
const childrenCodes = queryCodeArray(code, item.children);
if (childrenCodes.length) {
return [...codes, ...childrenCodes];
}
}
}
return [];
}

console.log(queryCodeArray('10', arr));
// []
console.log(queryCodeArray('12', arr));
// [ '12' ]
console.log(queryCodeArray('23', arr));
// ['12', '23']
console.log(queryCodeArray('46', arr));
// [ '12', '23', '35', '46' ]

``````
``````function findpath(root,stack,findvalue) {
let b = false;
if (root != null) {
stack.push(root);
if(root.code===findvalue){return true}
var children = root.children;
if(children){
for (var i = 0; i < children.length; i++){
b = findpath(children[i],stack,findvalue);
if(b){
break;
}
}
}
if(!b){
stack.pop();
}
}
return b;
}

const stack=[]
const d=findpath(arr[0],stack,'45')
console.log(stack)``````

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进