Simple Binary Tree

Algorithm 2021. 3. 5. 09:39
반응형
using System;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Simple Binary Tree");
            var tree = new SBTree();
            var a = 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");

            a.leftChild = b;
            b.leftChild = c;
            b.rightChild = d;

            a.rightChild = e;
            e.leftChild = f;
            e.rightChild = g;

            Console.WriteLine("Preorder");
            tree.PreorderPrint(a);
            Console.WriteLine();

            Console.WriteLine("Inorder");
            tree.InorderPrintTree(a);
            Console.WriteLine();

            Console.WriteLine("Postorder");
            tree.PostorderPrintTree(a);
            Console.WriteLine();

            tree.DestoryTree(a);
        }
    }
}
using System;
public class Node{
    public Node leftChild;
    public Node rightChild;
    public string data;
    public Node(string data){
        this.data = data;
    }
}
public class SBTree{
    public SBTree(){

    }
    public Node CreateNode(string data){
        var node = new Node(data);
        return node;
    }
    public void DestoryNode(Node node){
        node = null;
    }
    //Preorder 
    public void PreorderPrint(Node node){
        if(node == null) return;
        Console.Write(" {0}", node.data);
        this.PreorderPrint(node.leftChild);
        this.PreorderPrint(node.rightChild);
    }
    //Inorder
    public void InorderPrintTree(Node node){
        if(node == null) return;
        this.InorderPrintTree(node.leftChild);
        Console.Write(" {0}", node.data);   //root
        this.InorderPrintTree(node.rightChild);
    }
    //Postorder
    public void PostorderPrintTree(Node node){
        if(node == null) return;
        this.PostorderPrintTree(node.leftChild);
        this.PostorderPrintTree(node.rightChild);
        Console.Write(" {0}", node.data); //root
    }
    //Delete Tree (Postorder)
    public void DestoryTree(Node root){
        if(root == null) return;
        this.DestoryTree(root.leftChild);
        this.DestoryTree(root.rightChild);
        this.DestoryTree(root);
    }
}

반응형

'Algorithm' 카테고리의 다른 글

C# Array  (0) 2021.03.15
C# LinkedList  (0) 2021.03.15
LCRSTree  (0) 2021.03.04
완주하지 못한 선수  (0) 2021.01.07
C# program to implement Binary Search Tree  (0) 2020.10.23
: