算法:在树中查找某个结点并返回该节点路径(js实现)

题目要求:

给定一个树,给定一个节点id,返回从root到该节点的path、以及该节点的所有叶节点id,格式见return

  • @param {object: { _id: number, children: [ tree ] }} tree
  • @param {number} id
  • @return { path: ‘1-3-6’, leaves: [ 9, 10 ] }
  • @example

具体实现如下:


const exampleTree = {
        _id: 1,
        children: [{
            _id: 2,
            children: [{
                _id: 4,
                children: [{
                    _id: 7,
                    children: []
                }]
            }, {
                _id: 5,
                children: []
            }]
        }, {
            _id: 3,
            children: [{
                _id: 6,
                children: [{
                    _id: 8,
                    children: [{
                        _id: 10,
                        children: []
                    }]
                }, {
                    _id: 9,
                    children: []
                }]
            }]
        }]
    }
    //例子
    // const exampleId = 6 //输入的id
    // const exampleResult = { //输出的结果格式
    //     path: '1-3-6',
    //     leaves: [9, 10]
    // }

//主执行函数
function searchTree(tree, id) {
    let res = findNode(tree, id)

    //边界处理,输入的id不存在相对应的节点时
    if (res == undefined) {
        return '在该树的中没有相对应的id的节点'
    }

    res.path.unshift(tree._id)
    let path = res.path.join('-')
    let node = res.node
    let leaves = findLeaves(node)
    return {
        path,
        leaves
    }
}

// 深度遍历查找目标节点及缓存相关路径
function findNode(tree, id) {

    if (tree._id == id) {
        return {
            path: [],
            node: tree
        }
    }

    let res;
    for (let i = 0; i < tree.children.length; i++) {
        res = findNode(tree.children[i], id)
        if (res != undefined) {
            res.path.unshift(tree.children[i]._id)
            return res
        }
    }
    return undefined
}

// 递归获取叶子节点
function findLeaves(node) {

    if (node.children.length == 0) {
        return [node._id]
    }
    let leaves = []
    for (let i = 0; i < node.children.length; i++) {
        res = findLeaves(node.children[i])
        leaves = res.concat(leaves)
    }
    return leaves
}
console.log(searchTree(exampleTree, 6));

测试例子1:

console.log(searchTree(exampleTree, 6));

结果:
算法:在树中查找某个结点并返回该节点路径(js实现)_第1张图片
测试例子2:

console.log(searchTree(exampleTree, 11));

结果:
算法:在树中查找某个结点并返回该节点路径(js实现)_第2张图片

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