Toy#7 treeDFS

tia·2021년 12월 3일
0

알고리즘

목록 보기
6/9
post-thumbnail

문제

임의의 tree를 구성하는 노드 중 하나의 Node 객체를 입력받아, 해당 노드를 시작으로 깊이 우선 탐색(DFS, Depth First Search)을 합니다. 이 때, 탐색되는 순서대로 노드의 값이 저장된 배열을 리턴해야 합니다.

let root = new Node(1);
let rootChild1 = root.addChild(new Node(2));
let rootChild2 = root.addChild(new Node(3));
let leaf1 = rootChild1.addChild(new Node(4));
let leaf2 = rootChild1.addChild(new Node(5));
let output = dfs(root);
console.log(output); // --> [1, 2, 4, 5, 3]

leaf1.addChild(new Node(6));
rootChild2.addChild(new Node(7));
output = dfs(root);
console.log(output); // --> [1, 2, 4, 6, 5, 3, 7]

풀이

1. 도전!

let dfs = function (node) {
  // 리턴값 배열 선언
  let result = [];

  // 재귀함수를 아마도 이용해야 할 듯?
  // 탐색 node에 node.children가 존재 하는 경우 => node.value 푸쉬 후 재귀함수
  // node.children이 없다면 => node.value 푸시

  const crashDfs = (node)=> {
    result.push(node.value);
    if(node.children){
      for(let i=0; i<node.children.length;i++){
        crashDfs(node.children[i]);
      }
    } 
  }

  crashDfs(node);
  return result
};

// 이 아래 코드는 변경하지 않아도 됩니다. 자유롭게 참고하세요.
let Node = function (value) {
  this.value = value;
  this.children = [];
};

// 위 Node 객체로 구성되는 트리는 매우 단순한 형태의 트리입니다.
// membership check(중복 확인)를 따로 하지 않습니다.
Node.prototype.addChild = function (child) {
  this.children.push(child);
  return child;
};

2. 레퍼런스 코드

let dfs = function (node) {
  let values = [node.value];

  node.children.forEach((n) => {
    values = values.concat(dfs(n));
  });

  return values;
};

✅ 와... 이렇게나 간단하게?

0개의 댓글

관련 채용 정보