007. treeDFSelect

BenKim·2020년 7월 26일
0

treeDFSelect
주어진 Tree 클래스에 DFSelect 메소드를 구현하세요.
DFSelect 매소드의 요구사항은 아래와 같습니다.
filter 함수를 매개변수로 받습니다.
tree 의 각 node는 해당 filter 함수를 깊이 우선 방식으로 호출합니다.
filter 함수를 만족(return true)하는 tree의 node를 1차원 배열로 반환합니다.
let root1 = new Tree(1);
let branch2 = root1.addChild(2);
let branch3 = root1.addChild(3);
let leaf4 = branch2.addChild(4);
let leaf5 = branch2.addChild(5);
let leaf6 = branch3.addChild(6);
let leaf7 = branch3.addChild(7);
root1.DFSelect(function (value, depth) {
return value % 2;
})
// [1, 5, 3, 7]
root1.DFSelect(function (value, depth) {
return depth === 1;
})
// [2, 3]

내가 작성한 코드

Tree.prototype.DFSelect = function(filter, depth, results) {
  results = results || []; // 재귀를 사용할 때 굉장히 편리한것 같다. or연산자인데 첫째값이 참이면 첫째값을,
  depth = depth || 0; // 첫째값이 거짓이면 두번째값을 갖는다.

  if (filter(this.value,depth)) {
    results.push(this.value);
  }

  if(this.children){ // 만약 자식노드가 있다면 해당 함수를 재귀적으로 실행시킨다. 
  for (var i = 0; i < this.children.length; i++) {
    var child = this.children[i];
    child.DFSelect(filter,depth+1,results);
  }
  }
  return results;
};


profile
연습과 자신감

0개의 댓글