Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Printing Binary Tree in PreOrder, InOrder and PostOrder - C#

DZone's Guide to

Printing Binary Tree in PreOrder, InOrder and PostOrder - C#

·
Free Resource
Printing Tree in PreOrder, InOrder and PostOrder - C#
    public class BinaryTreeNode
    {
        public BinaryTreeNode Left { get; set; }

        public BinaryTreeNode Right { get; set; }

        public int Data { get; set; }

        public BinaryTreeNode(int data)
        {
            this.Data = data;
        }
    }

        public enum TreeTraversal
        {
            PREORDER,
            INORDER,
            POSTORDER
        }

        public void PrintTree(BinaryTreeNode root, TreeTraversal treeTraversal)
        {
            Action
 
   printValue = delegate(int v)
            {
                Console.Write(v + " ");
            };
        
            switch (treeTraversal)
            {
                case TreeTraversal.PREORDER:
                    PreOrderTraversal(printValue, root);
                    break;
                case TreeTraversal.INORDER:
                    InOrderTraversal(printValue, root);
                    break;
                case TreeTraversal.POSTORDER:
                    PostOrderTraversal(printValue, root);
                    break;
                default: break;
            }
        }

        public void PreOrderTraversal(Action
  
    action, BinaryTreeNode root)
        {
            if (root == null)
                return;

            action(root.Data);
            PreOrderTraversal(action, root.Left);
            PreOrderTraversal(action, root.Right);
        }

        public void InOrderTraversal(Action
   
     action, BinaryTreeNode root)
        {
            if (root == null)
                return;

            InOrderTraversal(action, root.Left);
            action(root.Data);
            InOrderTraversal(action, root.Right);
        }

        public void PostOrderTraversal(Action
    
      action, BinaryTreeNode root)
        {
            if (root == null)
                return;

            PostOrderTraversal(action, root.Left);
            PostOrderTraversal(action, root.Right);
            action(root.Data);
        }
    
   
  
 
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}