LCRSTree
Algorithm 2021. 3. 4. 23:12반응형
using System;
namespace dotnet
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("LCRSTree");
var tree = new LCRSTree();
var root = tree.CreateNode("A");
var b = tree.CreateNode("B");
var c = tree.CreateNode("C");
var d = tree.CreateNode("D");
var e = tree.CreateNode("E");
var f = tree.CreateNode("F");
var g = tree.CreateNode("G");
var h = tree.CreateNode("H");
var i = tree.CreateNode("I");
var j = tree.CreateNode("J");
var k = tree.CreateNode("K");
tree.AddChildNode(root, b);
tree.AddChildNode(b, c);
tree.AddChildNode(b, d);
tree.AddChildNode(d, e);
tree.AddChildNode(d, f);
tree.AddChildNode(root, g);
tree.AddChildNode(g, h);
tree.AddChildNode(root, i);
tree.AddChildNode(i, j);
tree.AddChildNode(j, k);
tree.PrintTree(root, 0);
tree.DestoryTree(root);
}
}
}
public class Node {
public Node leftChild;
public Node rightSibling;
public string data;
public Node(string data){
this.data = data;
}
}
public class LCRSTree{
public LCRSTree(){
}
public Node CreateNode(string data){
Node node = new Node(data);
return node;
}
public void DestoryNode(Node node){
node = null;
}
public void DestoryTree(Node root){
if(root.rightSibling != null){
this.DestoryTree(root.rightSibling);
}
if(root.leftChild != null){
this.DestoryTree(root.leftChild);
}
root.leftChild = null;
root.rightSibling = null;
this.DestoryNode(root);
}
public void AddChildNode(Node parent, Node child){
if(parent.leftChild == null){
parent.leftChild = child;
}else{
Node temp = parent.leftChild;
while(temp.rightSibling != null){
temp = temp.rightSibling;
}
temp.rightSibling = child;
}
}
public void PrintTree(Node node, int depth){
int i = 0;
for(i = 0; i<depth; i++){
System.Console.Write(" ");
}
System.Console.WriteLine(node.data);
if(node.leftChild != null){
this.PrintTree(node.leftChild, depth+1);
}
if(node.rightSibling != null){
this.PrintTree(node.rightSibling, depth);
}
}
}
반응형
'Algorithm' 카테고리의 다른 글
C# LinkedList (0) | 2021.03.15 |
---|---|
Simple Binary Tree (0) | 2021.03.05 |
완주하지 못한 선수 (0) | 2021.01.07 |
C# program to implement Binary Search Tree (0) | 2020.10.23 |
실전 알고리즘 강좌 바킹독 (0) | 2020.10.23 |