算法-遞歸算法(js樹形結構)


大家可能對遞歸算法並不陌生,但是在我們實戰項目中遇到需要使用遞歸算法的時候不知道如何下手。下面是我個人總結出來的經驗,如果有不對的地方歡迎大家指正。

遞歸算法使用步驟:
  第一步
    分析目標數據規律:大多數記錄的pid都對應了某記錄的ID
  第二步
    分析預期結果:預期結果是否可以通過分析出來的規則直接或間接實現
  第三步
    確定每次遞歸的參數和遞歸終止條件
下面我以常見的多級分類(js樹形結構)為例:
 1 const _ = require('lodash')
 2 let a = [{
 3     id: 1,
 4     pid: 0
 5 }, {
 6     id: 2,
 7     pid: 1
 8 }, {
 9     id: 3,
10     pid: 2
11 }, {
12     id: 4,
13     pid: 1
14 }, {
15     id: 5,
16     pid: 2
17 }, {
18     id: 6,
19     pid: 4
20 }]
21 /**
22  * 遞歸使用:
23  * 前提:是否有規律
24  * 第一步分析目標數據規律:
25  *  規律:大多數記錄的pid都對應了某記錄的ID
26  * 第二步分析預期結果:
27  *  預期結果:{id:xx,pid:xx,children:[{id:xx,pid:x, ...},...]}
28  *  預期結果是否可以通過分析出來的規則直接或間接實現
29  * 第三步確定每次遞歸的參數和遞歸終止條件
30  */
31 let aHandle = _.groupBy(a, 'pid')  // 運行結果:{"0":[{"id":1,"pid":0}],"1":[{"id":2,"pid":1},{"id":4,"pid":1}],"2":[{"id":3,"pid":2},{"id":5,"pid":2}],"4":[{"id":6,"pid":4}]}
32 let b = formatTree(aHandle, '0', 'id')
33 console.log(JSON.stringify(b))
34 
35 function formatTree(items, parentId, cKey) {
36     let result: any[] = []
37     if (!items[parentId]) {
38         return result
39     }
40     for (let t of items[parentId]) {
41         const temp = formatTree(items, t[cKey], cKey)
42         if (temp.length > 0) {
43             t.children = temp
44         }
45         result.push(t)
46     }
47     return result
48 }

運行結果如下:

 1 [
 2     {
 3         "id":1,
 4         "pid":0,
 5         "children":[
 6             {
 7                 "id":2,
 8                 "pid":1,
 9                 "children":[
10                     {
11                         "id":3,
12                         "pid":2
13                     },
14                     {
15                         "id":5,
16                         "pid":2
17                     }
18                 ]
19             },
20             {
21                 "id":4,
22                 "pid":1,
23                 "children":[
24                     {
25                         "id":6,
26                         "pid":4
27                     }
28                 ]
29             }
30         ]
31     }
32 ]

 


免責聲明!

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



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