首頁 >後端開發 >C#.Net教程 >C#分別以前序遍歷、中序遍歷和後序遍歷列印二元樹

C#分別以前序遍歷、中序遍歷和後序遍歷列印二元樹

大家讲道理
大家讲道理原創
2016-11-10 16:08:221942瀏覽

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