This article describes the method of printing binary trees using preorder traversal, in-order traversal and post-order traversal. Share it for your reference. The specific implementation method is as follows:
public class BinaryTreeNode { public BinaryTreeNode Left { get; set; } public BinaryTreeNode Right { get; set; } public int Data { get; set; } public BinaryTreeNode(int data) { = data; } } public enum TreeTraversal { PREORDER, INORDER, POSTORDER } public void PrintTree(BinaryTreeNode root, TreeTraversal treeTraversal) { Action<int> printValue = delegate(int v) { (v + " "); }; switch (treeTraversal) { case : PreOrderTraversal(printValue, root); break; case : InOrderTraversal(printValue, root); break; case : PostOrderTraversal(printValue, root); break; default: break; } } public void PreOrderTraversal(Action<int> action, BinaryTreeNode root) { if (root == null) return; action(); PreOrderTraversal(action, ); PreOrderTraversal(action, ); } public void InOrderTraversal(Action<int> action, BinaryTreeNode root) { if (root == null) return; InOrderTraversal(action, ); action(); InOrderTraversal(action, ); } public void PostOrderTraversal(Action<int> action, BinaryTreeNode root) { if (root == null) return; PostOrderTraversal(action, ); PostOrderTraversal(action, ); action(); }
I hope this article will be helpful to everyone's C# programming.