JS 简单树形 断路径数组 拼接成多个路径

简单 树形 断点路径数组 拼接成路径数组

       let aarr = [
            [1, 2],
            [1, 3],
            [2, 4],
            [4, 5],
            [4, 6],
            [3, 7],
            [7, 9],
            [3, 8],
            [8, 10]
        ]//断点路径数组
        let pathAry = [];//存放所有的路径的数组
        let rootNode = 1;//根节点
        let nPath = [];//初始单一路径

        function findPath(arr, tNode, nPath) {
    
    

            console.log('当前节点:', tNode, '当前路径', nPath);

            let aaa = arr.filter(item => item[0] == tNode);
            if (aaa.length > 1) {
    
    
                //分支节点 多子 父节点
                for (let i = 0; i < aaa.length; i++) {
    
    
                    let ary = [...nPath, tNode];
                    findPath(arr, aaa[i][1], ary)
                }
            } else if (aaa.length == 1) {
    
    
                	//单子 父节点
                    nPath.push(tNode);
                    return findPath(arr, aaa[0][1], nPath)
            	} else {
    
    
                    //无子节点 末端
                    nPath.push(tNode);
                    pathAry.push(nPath);
                    return nPath;
                }
        }
        let a = findPath(aarr, rootNode, nPath);

猜你喜欢

转载自blog.csdn.net/cxllRNGNB/article/details/109097213