Home > Backend Development > C#.Net Tutorial > C# uses pre-order traversal, in-order traversal and post-order traversal to print binary trees.

C# uses pre-order traversal, in-order traversal and post-order traversal to print binary trees.

大家讲道理
Release: 2016-11-10 16:08:22
Original
1940 people have browsed it

C# prints binary trees using pre-order traversal, in-order traversal and post-order traversal respectively

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);
    }
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template