CShap 二叉树前序遍历 源代码
时间: 2023-09-19 12:08:22 浏览: 51
以下是 C# 中二叉树前序遍历的源代码:
```
using System;
public class Node {
public int data;
public Node left;
public Node right;
public Node(int item) {
data = item;
left = right = null;
}
}
public class BinaryTree {
Node root;
public BinaryTree() {
root = null;
}
void printPreorder(Node node) {
if (node == null) {
return;
}
Console.Write(node.data + " ");
printPreorder(node.left);
printPreorder(node.right);
}
void printPreorder() {
printPreorder(root);
}
public static void Main() {
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
Console.WriteLine("Preorder traversal of binary tree is ");
tree.printPreorder();
}
}
```
在这个示例代码中,我们首先定义了一个 `Node` 类表示二叉树中的每个节点,其中包含该节点的数据、左子节点和右子节点。然后,我们定义了一个 `BinaryTree` 类表示整个二叉树,其中包含根节点和打印前序遍历的方法。在 `printPreorder` 方法中,我们首先打印当前节点的数据,然后递归遍历左子树和右子树。最后,在 `Main()` 方法中,我们创建了一个二叉树并打印了它的前序遍历结果。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)