js 深度遍历 两种方法

 

 

let tree = { id: '1', children: [ { id:'1-1', }, { id: '1-2', children: [{ id: '2', children: [{ id: '2-1', children: [ { id: '2-2' } ] }] }] } ] }

1、递归写法

let deep =  (node) => {
    let nodes = [];
    let stack = [];

    stack.push(node);
    while(stack.length) {
        console.log(stack)
        let item = stack.shift();
        let children = item.children;
        nodes.push(item.id)
        if(children) {
            for(let i = 0; i < children.length; i++) {
                stack.push(children[i])
            }
        }
    }
    return nodes;
   
}

2、迭代写法

let deep = (node,nodeList = []) => {
    nodeList.push(node.id)
    if(node.children && node.children.length > 0) {
        let children = node.children
        for(let i = 0; i < children.length; i++ ){
            console.log(nodeList)
            deep(children[i], nodeList)
        }
    }
    return nodeList;
}