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#程序设计有所帮助。
赞 (0)