BST (Binary Search Tree)

Algorithm 2023. 1. 16. 15:59
반응형
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStructure
{
    class BST
    {
        public class Node {
            public int data;
            public Node left;
            public Node right;
            public Node(int data) {
                this.data = data;
            }
        }

        public Node root;
        //생성자 
        public BST() { 

        }

        public void MakeTree(int[] arr) {
            root = MakeTree(arr, 0, arr.Length - 1);    //0 ~ 9
        }

        public Node MakeTree(int[] arr, int start, int end) {
            if (start > end) return null;

            int mid = (start + end) / 2;
            Node node = new Node(arr[mid]);
            node.left = MakeTree(arr, start, mid - 1);
            node.right = MakeTree(arr, mid + 1, end);
            return node;
        }

        public void TraverseInOrder(Node root) {
            if (root == null) return;
            this.TraverseInOrder(root.left);
            Console.Write("{0} ", root.data);
            this.TraverseInOrder(root.right);
        }


    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStructure
{
    class App
    {
        public App() {
            int[] arr = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            var bst = new BST();
            bst.MakeTree(arr);
            bst.TraverseInOrder(bst.root);
        }
    }
}

반응형

'Algorithm' 카테고리의 다른 글

[BOJ] 1406 에디터  (0) 2023.01.17
[알고스팟] 록 페스티벌 C#  (0) 2023.01.17
LCRS Tree  (0) 2023.01.16
[BOJ] 1874 스택 수열  (0) 2023.01.16
[BOJ] 9093 단어 뒤집기  (0) 2023.01.16
: