温馨提示×

C# treenode怎样实现搜索

c#
小樊
91
2024-07-16 15:58:56
栏目: 编程语言

要在C#中实现对TreeNode的搜索,可以使用递归算法来实现。以下是一个示例代码,展示了如何在一个简单的二叉树中搜索特定的值:

using System;

public class TreeNode
{
    public int value;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(int v)
    {
        value = v;
        left = null;
        right = null;
    }
}

public class Tree
{
    public TreeNode root;

    public Tree()
    {
        root = null;
    }

    public TreeNode Search(TreeNode node, int target)
    {
        if (node == null || node.value == target)
        {
            return node;
        }

        TreeNode leftResult = Search(node.left, target);
        TreeNode rightResult = Search(node.right, target);

        if (leftResult != null)
        {
            return leftResult;
        }
        else
        {
            return rightResult;
        }
    }
}

class Program
{
    static void Main()
    {
        Tree tree = new Tree();
        tree.root = new TreeNode(1);
        tree.root.left = new TreeNode(2);
        tree.root.right = new TreeNode(3);
        tree.root.left.left = new TreeNode(4);
        tree.root.left.right = new TreeNode(5);
        tree.root.right.left = new TreeNode(6);
        tree.root.right.right = new TreeNode(7);

        TreeNode result = tree.Search(tree.root, 5);

        if (result != null)
        {
            Console.WriteLine("Found value: " + result.value);
        }
        else
        {
            Console.WriteLine("Value not found");
        }
    }
}

在上面的示例中,我们定义了一个简单的二叉树结构,并实现了一个Search方法来搜索特定的值。在Main方法中,我们创建了一个树实例,并调用Search方法来搜索值为5的节点。如果找到了对应的节点,将会打印出节点的值;否则,将会打印出“Value not found”。

0