# 递归算法 &nbsp;&nbsp;&nbsp;&nbsp;测试数据 ```JavaScript let a = [ {id:1, name:'贵州省', pid:0}, {id:2, name:'遵义市', pid:1}, {id:3, name:'泸州市', pid:4}, {id:4, name:'四川省', pid:0}, {id:5, name:'赤水市', pid:2} ] ``` ## 关系梳理 ```JavaScript function tree(arr, id, n) { for (let i=0; arr.length>i; i++) { if (id == arr[i].pid) { console.log(' '.repeat(n) + arr[i].name) tree(arr, arr[i].id, n+1) } } } tree(arr, 0, 0) ``` **输出** ```JavaScript '贵州省' ' 遵义市' ' 赤水市' '四川省' ' 泸州市' ``` <br /><br /> ## 树结构查询 ```JavaScript function tree(arr, id) { let res = [] for (let i=0; arr.length>i; i++) { if (id == arr[i].pid) { arr[i].child = tree(arr, arr[i].id) res.push(arr[i]) } } return res } tree(a, 0) ``` **输出** ```javascript [ { id: 1, name: "贵州省", pid: 0, child: [ { id: 2, name: "遵义市", pid: 1, child: [{ id: 5, name: "赤水市", pid: 2, child: [] }], }, ], }, { id: 4, name: "四川省", pid: 0, child: [{ id: 3, name: "泸州市", pid: 4, child: [] }], }, ] ```