首页  >  文章  >  后端开发  >  C#分别用前序遍历、中序遍历和后序遍历打印二叉树

C#分别用前序遍历、中序遍历和后序遍历打印二叉树

大家讲道理
大家讲道理原创
2016-11-10 16:08:221922浏览

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);
    }
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn