溫馨提示×

C# treenode怎樣實現(xiàn)搜索

c#
小樊
91
2024-07-16 15:58:56
欄目: 編程語言

要在C#中實現(xiàn)對TreeNode的搜索,可以使用遞歸算法來實現(xiàn)。以下是一個示例代碼,展示了如何在一個簡單的二叉樹中搜索特定的值:

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");
        }
    }
}

在上面的示例中,我們定義了一個簡單的二叉樹結(jié)構(gòu),并實現(xiàn)了一個Search方法來搜索特定的值。在Main方法中,我們創(chuàng)建了一個樹實例,并調(diào)用Search方法來搜索值為5的節(jié)點。如果找到了對應(yīng)的節(jié)點,將會打印出節(jié)點的值;否則,將會打印出“Value not found”。

0