File tree Expand file tree Collapse file tree 3 files changed +100
-0
lines changed
bona1122/[week5]Tree/Binary_search_tree Expand file tree Collapse file tree 3 files changed +100
-0
lines changed Original file line number Diff line number Diff line change 1+ // https://www.acmicpc.net/problem/5639
2+ // 이진 검색트리의 전위 순회 경과가 주어지면, 후위순회 결과 구하기
3+ const filePath =
4+ process . platform === "linux"
5+ ? "/dev/stdin"
6+ : require ( "path" ) . join ( __dirname , "input.txt" )
7+ const input = require ( "fs" ) . readFileSync ( filePath ) . toString ( ) . trim ( ) . split ( "\n" )
8+ const log = console . log
9+
10+ const arr = input . map ( Number )
11+
12+ const postorder = ( root , end ) => {
13+ if ( root > end ) return
14+
15+ let right = end + 1 // 오른쪽 서브트리(루트보다 큰 요소들) 시작점 구하기
16+ for ( let i = root + 1 ; i <= end ; i ++ ) {
17+ if ( arr [ i ] > arr [ root ] ) {
18+ right = i
19+ break
20+ }
21+ }
22+
23+ // 후위 순위로 출력
24+ postorder ( root + 1 , right - 1 )
25+ postorder ( right , end )
26+ log ( arr [ root ] )
27+ }
28+
29+ postorder ( 0 , arr . length - 1 )
Original file line number Diff line number Diff line change 1+ // https://www.acmicpc.net/problem/5639
2+ // 이진 검색트리의 전위 순회 경과가 주어지면, 후위순회 결과 구하기
3+
4+ // 핵심: BST의 전위순회 결과가 있기에, 순서대로 트리에 삽입하면 트리가 복원된다
5+ const filePath =
6+ process . platform === "linux"
7+ ? "/dev/stdin"
8+ : require ( "path" ) . join ( __dirname , "input.txt" )
9+ const input = require ( "fs" ) . readFileSync ( filePath ) . toString ( ) . trim ( ) . split ( "\n" )
10+ const log = console . log
11+
12+ const arr = input . map ( Number )
13+
14+ class Node {
15+ constructor ( value ) {
16+ this . value = value
17+ this . left = null
18+ this . right = null
19+ }
20+ }
21+
22+ class BinarySearchTree {
23+ constructor ( ) {
24+ this . root = null
25+ }
26+
27+ insert ( value ) {
28+ if ( ! this . root ) {
29+ this . root = new Node ( value )
30+ return
31+ }
32+
33+ let current = this . root
34+ while ( true ) {
35+ if ( value < current . value ) {
36+ if ( ! current . left ) {
37+ current . left = new Node ( value )
38+ break
39+ }
40+ current = current . left
41+ } else {
42+ if ( ! current . right ) {
43+ current . right = new Node ( value )
44+ break
45+ }
46+ current = current . right
47+ }
48+ }
49+ }
50+
51+ postorder ( node = this . root ) {
52+ if ( ! node ) return
53+
54+ this . postorder ( node . left ) // 왼쪽 서브트리 순회
55+ this . postorder ( node . right ) // 오른쪽 서브트리 순회
56+ log ( node . value ) // 현재 노드 출력
57+ }
58+ }
59+
60+ const tree = new BinarySearchTree ( )
61+ arr . forEach ( ( item ) => tree . insert ( item ) )
62+ tree . postorder ( )
Original file line number Diff line number Diff line change 1+ 50
2+ 30
3+ 24
4+ 5
5+ 28
6+ 45
7+ 98
8+ 52
9+ 60
You can’t perform that action at this time.
0 commit comments