전위 순회로 초기에 돌기 때문에 첫 번째 값이 루트 노드가 된다.
루트 노드를 정하고 data
를 모두 확인하면서 이진 검색 트리를 만족하도록 트리를 구성했다.
트리를 구성한 후에는 후위 순회를 돌아 출력하여 답을 구했다.
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const data = input.map(Number);
class Node {
constructor(v) {
this.value = v;
this.left = null;
this.right = null;
}
insert(v) {
if (v < this.value) {
if (!this.left) this.left = new Node(v);
else this.left.insert(v);
} else {
if (!this.right) this.right = new Node(v);
else this.right.insert(v);
}
}
}
const postOrder = (node) => {
node.left && postOrder(node.left);
node.right && postOrder(node.right);
console.log(node.value);
};
const solution = (data) => {
const root = new Node(data[0]);
for (let i = 1; i < data.length; i++) {
root.insert(data[i]);
}
postOrder(root);
};
solution(data);