티스토리 뷰

https://www.acmicpc.net/problem/5639

 

5639번: 이진 검색 트리

트리를 전위 순회한 결과가 주어진다. 노드에 들어있는 키의 값은 106보다 작은 양의 정수이다. 모든 값은 한 줄에 하나씩 주어지며, 노드의 수는 10,000개 이하이다. 같은 키를 가지는 노드는 없다

www.acmicpc.net

class Node{
  constructor(data,left,right){
    this.data = data;
    this.left = left;
    this.right = right;
  }
  show(){
    return this.data; 
  }
}


class BST{
  constructor(){
    this.root = null;
    this.preOrderList = '';
    this.inOrderList = '';
    this.postOrderList = '';
  }

  insert(data){ 
    let n = new Node(data,null,null);
    if(this.root == null){ 
      this.root = n; 
    }else{ 
      let current = this.root; 
      let parent; 
      while(true){ 
        parent = current; 
        if(data<current.data){
          current = current.left; 
          if(current==null){ 
            parent.left = n; 
            break; 
          }
        }else{
          current = current.right; 
          if(current == null){ 
            parent.right = n; 
            break; 
          }
        }
      }
    }
  }
}


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

const tree = new BST();

input.forEach(v=>{
  tree.insert(v);
})


let postOrderList = [];

function postOrder(node){ 
  if((node != null)){ 
    postOrder(node.left);
    postOrder(node.right);
    postOrderList.push(node.data);
  }
}

postOrder(tree.root);

console.log(postOrderList.join('\n'))
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함