Outdated/Algorithm Solution

[BOJ] 5639번 이진 검색 트리

해달 2020. 6. 1. 08:00

복기

-


코드

  • C++ 17


#include <stdio.h>

 

int Tree[10001];

int N;

 

void preToPost(int node, int bound)

{

    // 오른쪽 서브트리의 시작 인덱스를 찾는다.

    int sub = node + 1;

    while (sub <= bound && Tree[sub] < Tree[node])

        ++sub;

 

    // 왼쪽 서브트리를 순회한다.

    int left = node + 1;

    if (left <= sub - 1)

        preToPost(left, sub - 1);

 

    // 오른쪽 서브트리를 순회한다.

    if (sub <= bound)

        preToPost(sub, bound);

 

    printf("%d\n", Tree[node]);

}

 

int main()

{

    N = 1;

    while (EOF != scanf("%d", &Tree[N]))

        ++N;

 

    preToPost(1, N - 1);

}


  • C# 6.0


using System;

using System.Collections.Generic;

using System.Security.Cryptography.X509Certificates;

 

namespace Csharp

{

    class Program

    {

        static int[] Tree = new int[10001];

 

        static void Main(string[] args)

        {

            int n = 1;

            while (true)

            {

                var input = Console.ReadLine();

                if (input == null || input == "")

                    break;

 

                Tree[n] = Convert.ToInt32(input);

                ++n;

            }

 

            PreToPost(1, n - 1);

        }

 

        static void PreToPost(int node, int bound)

        {

            int right = node + 1;

            while (right <= bound && Tree[right] < Tree[node])

                ++right;

 

            int left = node + 1;

            if (left <= right - 1)

                PreToPost(left, right - 1);

 

            if (right <= bound)

                PreToPost(right, bound);

 

            Console.WriteLine(Tree[node]);

        }

    }

}


  • Python 3


from sys import stdin, setrecursionlimit

setrecursionlimit(100000000)

 

Tree = [ int(x) for x in stdin.readlines() ]

 

def preToPost(tree, node, bound):

    right = node + 1

    while right <= bound and tree[right] < tree[node]:

        right += 1

 

    left = node + 1

    if left <= right - 1:

        preToPost(tree, left, right - 1)

    

    if right <= bound:

        preToPost(tree, right, bound)

    

    print(tree[node])

 

preToPost(Tree, 0, len(Tree) - 1)