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

结构的话最多四级层,也可能只有有一层,每层type是0123.
想要的结果是,
输入code 23 返回 ['12','23']
输入code 34 返回 ['12','23','34']
...
感谢各位

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

}]

}]

}]

}

]


回答:

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)

以上是 问一个tree数据结构向上取值的问题? 的全部内容, 来源链接: utcz.com/p/933678.html

回到顶部