C# Program to Implement Post-Order Traversal in Binary Tree

You are currently viewing C# Program to Implement Post-Order Traversal in Binary Tree

C# program to implement Post-order traversal in Binary Tree

//C# program to implement Post-order traversal in Binary Tree

using System;
using System.Collections.Generic;
using System.Text;

class Node
{
    public int  item        ;
    public Node left_ptr    ;
    public Node right_ptr   ;
    
}
class BinaryTree
{
    public Node root;
    public Node GetRoot()
    {
        return root;
    }
    public void Postorder_Traveser(Node rootNode)
    {
        if (rootNode != null)
        {
            Postorder_Traveser(rootNode.left_ptr);
            Postorder_Traveser(rootNode.right_ptr);
            Console.Write("{0} ", rootNode.item);
        }
    }
    public void InsertItem(int item)
    {
        Node curNode;
        Node parentNode;
        Node node = new Node();
        
        node.item = item;

        if (root != null)
        {
            curNode = root;

            while (true)
            {
                parentNode = curNode;
                if (item < curNode.item)
                {
                    curNode = curNode.left_ptr;
                    if (curNode == null)
                    {
                        parentNode.left_ptr = node;
                        break;
                    }
                }
                else
                {
                    curNode = curNode.right_ptr;
                    if (curNode == null)
                    {
                        parentNode.right_ptr = node;
                        break;
                    }
                }
            }
        }
        else
        {
            root = node;
        }
    }
    
}
class Demo
{
    static void Main(string[] args)
    {
        BinaryTree tree = new BinaryTree();
       
        tree.InsertItem(10);
        tree.InsertItem(15);
        tree.InsertItem(35);
        tree.InsertItem(26);
        tree.InsertItem(47);
        tree.InsertItem(34);
        tree.InsertItem(90);
        
        Console.WriteLine("Post-order Traversal : ");
        tree.Postorder_Traveser(tree.GetRoot());
        Console.WriteLine(" ");
    }
}

output

Post-order Traversal :
34 26 90 47 35 15 10
Press any key to continue . . .

Ranjith Kumar

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply