C#應用前序遍歷、中序遍歷和後序遍歷打印二叉樹的辦法。本站提示廣大學習愛好者:(C#應用前序遍歷、中序遍歷和後序遍歷打印二叉樹的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#應用前序遍歷、中序遍歷和後序遍歷打印二叉樹的辦法正文
本文實例講述了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<int> 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<int> action, BinaryTreeNode root) { if (root == null) return; action(root.Data); PreOrderTraversal(action, root.Left); PreOrderTraversal(action, root.Right); } public void InOrderTraversal(Action<int> action, BinaryTreeNode root) { if (root == null) return; InOrderTraversal(action, root.Left); action(root.Data); InOrderTraversal(action, root.Right); } public void PostOrderTraversal(Action<int> action, BinaryTreeNode root) { if (root == null) return; PostOrderTraversal(action, root.Left); PostOrderTraversal(action, root.Right); action(root.Data); }
願望本文所述對年夜家的C#法式設計有所贊助。