找到樹中指定id的所有父節點


const data = [{
    id: 1,
    children: [{
        id: 2,
        children: [{
            id: 3,
        }, {
            id: 4,
        }],
    }],
}, {
    id: 5,
    children: [{
        id: 6,
    }],
}];

let nodes = [];
function getParentNodes(id, tree) {
    _getParentNodes([], id, tree);
    return nodes;
}

function _getParentNodes(his, targetId, tree) {
    tree.some((list) => {
        const children = list.children || [];
        if (list.id === targetId) {
            nodes = his;
            return true;
        } else if (children.length > 0) {
            const history = [...his];
            history.push(list);
            return _getParentNodes(history, targetId, children);
        }
    })
}

  要找到一顆樹中指定id的那個節點很簡單。如果要找到指定的所有父節點,轉換一下思路就是將深度遍歷的每條順序都記錄下來,直到找到了指定id的節點時,輸出該條記錄。

  那么僅僅需要在每次遍歷時,將上一次的記錄傳過去即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM