알고리즘

DFS 재귀함수 (liquor tree)

junjunwon 2022. 4. 13. 17:46

vue liquor tree를 재귀함수로 호출하여 AD OU정보를 depth별로 동적으로 api로 가져오는 코드이다.

기존 코드로 작성할 경우 child를 추가할때 경로를 못찾는 문제가 있었다. 

아마 다시 작성하면 문제를 해결할 수 있었겠지만, 새로운 아이디어를 생각해보기로 결정했다.

굳이, depth의 모든 item을 순회할 필요가 있었는가?

item의 children이 있을때 재귀로 탐색하고, 동일한 id값이 있으면 return 없으면, 깊이 우선 탐색으로 진행하면 될 것으로 보였고, 결과는 성공이다.

 

기존 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
putTreeItem(items, targetNode, children) {
      // 타켓노드의 아이디와 일치하는 노드를 찾아서 노드 추가
      for (let n = 0; n < items.length; n++) {
        if (items[n]['distinguishedName'=== targetNode.id) {
          // items[n].children = children
          // this.addText(storeTree, items)
          // storeTree.commit('setRows', storeTree.state.rows)
          debugger
          this.addChildText(n, 0, items, children)
          storeTree.commit('setRows', storeTree.state.rows)
 
          // storeTree.commit('setRows', storeTree.state.rows)
          // storeTree.commit('appendChildren', {n, children})
          return
        } else {
          //타겟노드 아이디와 일치하지 않을 경우 자식 노드 탐색
          for(let i = 0; i < items[n].children.length; i++) {
            if (items[n].children[i]['distinguishedName'=== targetNode.id) {
              // items[n].children[i].children = children
 
              // this.addText(storeTree, items)
              // storeTree.commit('setRows', storeTree.state.rows)
 
              this.addChildText(n, i, items, children)
              storeTree.commit('setRows', storeTree.state.rows)
              // storeTree.commit('appendChildren', {n, i, children})
              return
            }
            else {
              //자식노드에도 없다면, 자식노드를 루트노드로 설정 -> 재귀 호출
              debugger
              this.putTreeItem(items[n].children[i].children, targetNode, children)
            }
          }
        }
      }
    },
cs

 

 

개선 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
putTreeItem(items, targetNode, children) {
      for (const object of Object.entries(items)) {
        if(object[1].distinguishedName !== targetNode.id) {
          if(Object.keys(object[1].children).length !== 0) {
            this.test(object[1].children, targetNode, children)
          }
        } else {
          this.testAdd(object[1], children)
          storeTree.commit('setRows', storeTree.state.rows)
          return
        }
        console.log(`${object[0]} : ${object[1].distinguishedName}`);
      }
    },
cs