[백준1991_자바스크립트(javascript)] - 트리 순회

경이·2025년 5월 5일

𝑩𝑶𝑱 (𝒋𝒔)

목록 보기
300/325

🔴 문제

트리 순회


🟡 Sol

const fs = require('fs');
const path = process.platform === 'linux' ? '/dev/stdin' : 'input.txt';
const inputs = fs.readFileSync(path).toString().trim().split('\n');
const n = Number(inputs.shift());
const tree = new Map();

for (const input of inputs) {
  const [node, left, right] = input.split(' ');

  tree.set(node, [left, right]);
}

let preOrderResult = '';
const preOrder = (node) => {
  const [left, right] = tree.get(node);
  preOrderResult += node;

  if (left !== '.') preOrder(left);
  if (right !== '.') preOrder(right);
};
preOrder('A');
console.log(preOrderResult);

let inOrderResult = '';
const inOrder = (node) => {
  const [left, right] = tree.get(node);

  if (left !== '.') inOrder(left);
  inOrderResult += node;
  if (right !== '.') inOrder(right);
};
inOrder('A');
console.log(inOrderResult);

let postOrderResult = '';
const postOrder = (node) => {
  const [left, right] = tree.get(node);

  if (left !== '.') postOrder(left);
  if (right !== '.') postOrder(right);
  postOrderResult += node;
};
postOrder('A');
console.log(postOrderResult);

🟢 풀이

⏰ 소요한 시간 : -

전위순회, 중위순회, 후위순회를 연습해보는 문제다.
친절하게도 문제에 전위순회, 중위순회, 후위순회가 뭔지 알려준다.
전위 순회는 node를 먼저 출력하고, 중위순회는 왼쪽자식을 먼저, 후위순회는 오른쪽 자식을 먼저 출력해주면 된다.


🔵 Ref

profile
록타르오가르

0개의 댓글