用c#写个二叉树前序遍历
时间: 2024-03-06 12:43:49 浏览: 76
以下是使用C#编写的二叉树前序遍历的示例代码:
```csharp
using System;
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
{
this.val = val;
this.left = left;
this.right = ;
}
}
public class BinaryTree
{
public void PreorderTraversal(TreeNode root)
{
if (root == null)
return;
Console.Write(root.val + " ");
PreorderTraversal(root.left);
PreorderTraversal(root.right);
}
}
public class Program
{
public static void Main(string[] args)
{
// 创建二叉树
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
// 前序遍历二叉树
BinaryTree bt = new BinaryTree();
Console.WriteLine("前序遍历结果:");
bt.PreorderTraversal(root);
}
}
```
阅读全文