基本上是使用深度優先遍歷的套路,以下方法獲取的是沿途的所有節點
export function getPathNodesByKey(root,stack,fCompare) { let b = false; if (root != null) { stack.push(root); if(fCompare(root)){return true} var children = root.children; if(children){ for (var i = 0; i < children.length; i++){ b = getPathByKey(children[i],stack,fCompare); if(b){ break; } } } if(!b){ stack.pop(); } } return b; } export function getAllPathNodesByKey(root,stack,fCompare) { let b = false; if (root != null) { stack.push(root); if(fCompare(root)){return true} var children = root.children; if(children){ for (var i = 0; i < children.length; i++){ b = getAllPathByKey(children[i],stack,fCompare); } } if(!b){ stack.pop(); } } return b; }
獲取沿途所有路徑
function getAllPathByKey(root,stack,fCompare,res) { if(root == null){ return; } stack.push(root); if(fCompare(root)){ res.push(JSON.parse(JSON.stringify(stack))); return; } var children = root.children; if(children){ for (var i = 0; i < children.length; i++){ getAllPathByKey(children[i],stack,fCompare,res); stack.pop(); } } } function getFisrtPathByKey(root,stack,fCompare,res) { if(root == null){ return; } stack.push(root); if(fCompare(root)){ res.push(JSON.parse(JSON.stringify(stack))); return true; } var children = root.children; if(children){ for (var i = 0; i < children.length; i++){ let hasNode = getFisrtPathByKey(children[i],stack,fCompare,res); stack.pop(); if(hasNode){ return true; } } } }
