JS 深度優先遍歷與廣度優先遍歷 實現查找


 

2.1.深度優先遍歷
深度優先查找(depth first search),采用棧結構,后進先出,JS用遞歸實現和沒有用遞歸實現

// 不用遞歸實現深度遍歷優先  
const depthFirstSearchWithoutRecursive = source => {
    const result = []; // 存放結果的數組
    // 當前棧內為全部數組
    const stack = JSON.parse(JSON.stringify(source));
    // 循環條件,棧不為空
    while (stack.length !== 0) {
      // 最上層節點出棧
      const node = stack.shift();
      // 存放節點
      result.push(node.id);
      // 如果該節點有子節點,將子節點存入棧中,繼續下一次循環
      const len = node.children && node.children.length;
      for (let i = len - 1; i >= 0; i -= 1) {
        stack.unshift(node.children[i]);
      }
    }
    return result;
  };
 
  const s = depthFirstSearchWithoutRecursive(root)
  console.log(s);// 結果為 [1, 2, 4, 5, 7, 8, 6, 3]

 


2.2.廣度優先遍歷
廣度優先查找(breadth first search),采用棧結構,后進先出,JS用遞歸實現和沒有用遞歸實現

  const breadthFirstSearch = source => {
    const result = []; // 存放結果的數組
    // 當前隊列為全部數據
    const queue = JSON.parse(JSON.stringify(source));
    // 循環條件,隊列不為空
    while (queue.length > 0) {
      // 第一個節點出隊列
      const node = queue.shift();
      // 存放結果數組
      result.push(node.id);
      // 當前節點有子節點則將子節點存入隊列,繼續下一次的循環
      const len = node.children && node.children.length;
      for (let i = 0; i < len; i += 1) {
        queue.push(node.children[i]);
      }
    }
    return result;
  };
 
  const s = breadthFirstSearch(root)
  console.log(s);// 結果為 [1, 2, 3, 4, 5, 6, 7, 8]

 

export const matchArea = function _matchArea(area: IArea[], content: string) {
  let matched: IArea[] = []
  if (!content || !area || !Array.isArray(area)) return matched

  area.forEach((item) => {
    if (content?.includes(item.name)) {
      matched.push(item)
    }
    if (item?.children) {
      const subMatch = _matchArea(item.children, content)
      matched = matched.concat(subMatch)
    }
  })
  return matched
}

 




免責聲明!

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



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