using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BinarySearchTree
{
public class BinaryTreeNode<T>
{
public T Data { get; set; }
public BinaryTreeNode<T> Left { get; set; }
public BinaryTreeNode<T> Right { get; set; }
public BinaryTreeNode(T data)
{
this.Data = data;
}
}
// // 이진검색트리 클래스스
public class BST<T>
{
private BinaryTreeNode<T> root = null;
private Comparer<T> comparer = Comparer<T>.Default;
public void Insert(T val)
{
BinaryTreeNode<T> node = root;
if (node == null)
{
root = new BinaryTreeNode<T>(val);
return;
}
while (node != null)
{
int result = comparer.Compare(node.Data, val);
if (result == 0)
{
//throw new InvalidDataException("Duplicate value");
return;
}
else if (result > 0)
{
if (node.Left == null)
{
node.Left = new BinaryTreeNode<T>(val);
return;
}
node = node.Left;
}
else
{
if (node.Right == null)
{
node.Right = new BinaryTreeNode<T>(val);
return;
}
node = node.Right;
}
}
}
public void PreOrderTraversal()
{
PreOrderRecursive(root);
}
private void PreOrderRecursive(BinaryTreeNode<T> node)
{
if (node == null) return;
Console.WriteLine(node.Data);
PreOrderRecursive(node.Left);
PreOrderRecursive(node.Right);
}
}
class Program
{
static void Main(string[] args)
{
BST<int> bst = new BST<int>();
bst.Insert(4);
bst.Insert(2);
bst.Insert(6);
bst.Insert(1);
bst.Insert(7);
bst.PreOrderTraversal();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BinarySearchTree
{
public class BinaryTreeNode<T>
{
public T Data { get; set; }
public BinaryTreeNode<T> Left { get; set; }
public BinaryTreeNode<T> Right { get; set; }
public BinaryTreeNode(T data)
{
this.Data = data;
}
}
// // 이진검색트리 클래스스
public class BST<T>
{
private BinaryTreeNode<T> root = null;
private Comparer<T> comparer = Comparer<T>.Default;
public void Insert(T val)
{
BinaryTreeNode<T> node = root;
if (node == null)
{
root = new BinaryTreeNode<T>(val);
return;
}
while (node != null)
{
int result = comparer.Compare(node.Data, val);
if (result == 0)
{
//throw new InvalidDataException("Duplicate value");
return;
}
else if (result > 0)
{
if (node.Left == null)
{
node.Left = new BinaryTreeNode<T>(val);
return;
}
node = node.Left;
}
else
{
if (node.Right == null)
{
node.Right = new BinaryTreeNode<T>(val);
return;
}
node = node.Right;
}
}
}
public void PreOrderTraversal()
{
PreOrderRecursive(root);
}
private void PreOrderRecursive(BinaryTreeNode<T> node)
{
if (node == null) return;
Console.WriteLine(node.Data);
PreOrderRecursive(node.Left);
PreOrderRecursive(node.Right);
}
}
class Program
{
static void Main(string[] args)
{
BST<int> bst = new BST<int>();
bst.Insert(4);
bst.Insert(2);
bst.Insert(6);
bst.Insert(1);
bst.Insert(7);
bst.PreOrderTraversal();
}
}
}
반응형
'프로그래밍 > C#' 카테고리의 다른 글
C# 재귀호출 (0) | 2019.03.24 |
---|---|
C# 정렬 sort (0) | 2019.03.24 |
C# 파일 읽기 (0) | 2019.03.24 |
C# 문자,숫자,영어,한글 구분 (0) | 2019.03.21 |
[C# 퀴즈 풀이]숫자구분자변환 (0) | 2018.03.26 |