c#二叉树的深度优先搜索实现

   2024-10-05 7200
核心提示:在C#中,可以使用递归的方式实现二叉树的深度优先搜索。以下是一个示例代码:using System;public class Node{public int data;p

在C#中,可以使用递归的方式实现二叉树的深度优先搜索。以下是一个示例代码:

using System;public class Node{    public int data;    public Node left, right;    public Node(int item)    {        data = item;        left = right = null;    }}public class BinaryTree{    Node root;    public BinaryTree()    {        root = null;    }    private void DepthFirstSearch(Node node)    {        if (node == null)            return;        Console.Write(node.data + " ");        DepthFirstSearch(node.left);        DepthFirstSearch(node.right);    }    public void DepthFirstSearch()    {        DepthFirstSearch(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("Depth First Search of binary tree is: ");        tree.DepthFirstSearch();    }}

在上面的示例中,首先定义了一个Node类来表示二叉树的节点,然后定义了一个BinaryTree类来表示二叉树。DepthFirstSearch方法用于递归地进行深度优先搜索,先访问当前节点,然后分别递归访问左子树和右子树。在Main方法中,创建一个二叉树并调用DepthFirstSearch方法进行深度优先搜索。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号