개발하기좋은날

treeDFS 본문

Algorithm

treeDFS

devbi 2022. 6. 2. 11:23
반응형
let dfs = function (node) {
  let values = [node.value];
  node.children.forEach((n) => {
    values = values.concat(dfs(n));
  });
  return values;
};

let Node = function (value) {
  this.value = value;
  this.children = [];
};


Node.prototype.addChild = function (child) {  
  this.children.push(child);
  return child;
};


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]

DFS 깊은 탐색 방법 

 

 

반응형

'Algorithm' 카테고리의 다른 글

binarySearch  (0) 2022.06.07
largestProductOfThree  (0) 2022.06.02
Bubble Sort  (0) 2022.05.25
isSubsetOf  (0) 2022.05.24
fibonacci  (0) 2022.05.23
Comments