깊이 우선 탐색 함수 만들기 (재귀, tree)

N·2022년 6월 30일
0

데일리코딩

목록 보기
2/3
//객체 생성 클래스
let Node = function (value) {
  this.value = value;
  this.children = [];
};

//클래스에 추가할 메소드
Node.prototype.addChild = function (child) {
  this.children.push(child);
  return child;
};

//깊이 우선 탐색 함수 만드는 코드
let dfs = function (node) {

  let result = [];

  //children이 빈배열 일 때 -> value를 push한 배열을 리턴
  if(node.children.length===0){
    result.push(node.value);
    return result;
  }

  //children이 빈배열이 아닐 때, 가장 먼저 value를 push하고
  result.push(node.value);

  // children 배열의 i번째 객체를 함수에 넣는다(재귀)
  for(let i=0; i<node.children.length; i++){
	result = result.concat(dfs(node.children[i]));
  }

  return result;
};


profile
web

0개의 댓글