[算法]查找树的节点,生成包含父节点的完整节点名

先上节点结构图

[算法]查找树的节点,生成包含父节点的完整节点名_第1张图片

需求:输出“北京资讯”的完整节点名字,形如:LGBT科普-防艾资讯-国内资讯-北京资讯(不包括根节点)

示例JSON:

let node = {
    "id": 7,
    "name": "首页",
    "child": [{
        "id": 153,
        "parent": 7,
        "name": "LGBT科普",
        "child": [{
            "id": 123,
            "parent": 153,
            "name": "多元性别"
        }, {
            "id": 124,
            "parent": 153,
            "name": "破除偏见"
        }, {
            "id": 125,
            "parent": 153,
            "name": "防艾资讯",
            "child": [{
                "id": 200,
                "parent": 125,
                "name": "国内资讯",
                "child": [{
                    "id": 201,
                    "parent": 200,
                    "name": "北京资讯"
                }]
            }]
        }]
    }]
};

思路:

首先查找目标节点,之后根据目标节点的parent属性反查父节点,直到得到准根节点的名字,利用递归,最终得到包含父节点的完整节点名。

代码:

const findNode = (nodeId, childNode) => {
    if (childNode.length && childNode.length > 0) {
        let targetNode = childNode.find(item => item.id == nodeId);
        if (targetNode) return targetNode;
        else {
            for (const item of childNode) {
                if (item.child){
                    targetNode = findNode(nodeId,item);
                    if (targetNode) break;
                }
            }
            if (targetNode) return targetNode;
            else return null;
        }
    } else if (childNode.id == nodeId) return childNode;
    else if (childNode.child) return findNode(nodeId,childNode.child);
    else return null;
  }
let fullName = (item) => {
    if (item.parent) {
        let nodeName = fullName(findNode(item.parent,node));
        return `${nodeName ? nodeName + "-" : ""}${item.name}`;
    }
    else return null;
}
console.log(fullName(findNode(201,node)));

需要注意的是,findNode函数需要两个参数,第一个参数是所要查找节点的id,第二个参数是在哪棵树里查找。

你可能感兴趣的:(算法,JavaScript,算法)