[백준] 트리 순회 #1991

welchs·2022년 2월 19일
0

알고리즘

목록 보기
36/44
post-thumbnail

후기

전위순회, 중위순회, 후위순회 복습 문제
오히려 이 문제는 input 값을 셋팅하는 것이 더 어려웠던 것 같다.

Node.js 풀이

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');

const N = Number(input[0]);

class Node {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

const dict = {};
input.slice(1).forEach((v) => {
  const [node, left, right] = v.split(' ');
  dict[node] = {
    left: left === '.' ? null : left,
    right: right === '.' ? null : right,
  };
});

const solution = (root) => {
  let preOrderAnswer = '';
  let inOrderAnswer = '';
  let postOrderAnswer = '';
  const preOrder = (node) => {
    const { left, right } = dict[node];
    preOrderAnswer += node;
    left && preOrder(left);
    right && preOrder(right);
  };
  const inOrder = (node) => {
    const { left, right } = dict[node];
    left && inOrder(left);
    inOrderAnswer += node;
    right && inOrder(right);
  };
  const postOrder = (node) => {
    const { left, right } = dict[node];
    left && postOrder(left);
    right && postOrder(right);
    postOrderAnswer += node;
  };
  preOrder(root);
  inOrder(root);
  postOrder(root);
  return `${preOrderAnswer}\n${inOrderAnswer}\n${postOrderAnswer}\n`;
};

console.log(solution('A'));
profile
고수가 되고 싶은 조빱

0개의 댓글