在二叉搜索树C#中查找节点值

时间:2017-03-08 19:15:25

标签: c# .net binary-search-tree

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class Node
    {
        public int Value { get; set; }

        public Node Left { get; set; }

        public Node Right { get; set; }

        public Node(int value, Node left, Node right)
        {
            Value = value;
            Left = left;
            Right = right;
        }
    }

    public class BinarySearchTree
    {
        public static bool Contains(Node root, int value)
        {
            bool status = false;
            if (root == null)
            {
                status = false;
            }
            else if (root.Value == value)
            {
                status = true;
                return true;
            }
            else if (root.Value < value)
            {
                Contains(root.Right, value);
            }
            else
            {
                Contains(root.Left, value);
            }
            return status;

        }

        public static void Main(string[] args)
        {
            Node n1 = new Node(1, null, null);
            Node n3 = new Node(3, null, null);
            Node n2 = new Node(2, n1, n3);

            Console.WriteLine(Contains(n2, 3));
            Console.ReadLine();
        }
    }
}

问题: 我也试过调试这段代码!但它一直显示错误的答案。让我知道我哪里错了。当我调试代码时,状态变为true但它仍然执行其他东西,最后变为false。让我知道我要去哪里

2 个答案:

答案 0 :(得分:3)

在递归调用中,您为子节点计算Contains,但不对其执行任何操作。您应该将结果值分配给status

public static bool Contains(Node root, int value)
{
    bool status = false;
    if (root == null)
    {
        status = false;
    }
    else if (root.Value == value)
    {
        status = true;
        return true;
    }
    else if (root.Value < value)
    {
        status = Contains(root.Right, value);
    }
    else
    {
        status = Contains(root.Left, value);
    }
    return status;
}

最好是避免使用此status变量并直接使用return语句:

public static bool Contains(Node root, int value)
{
    if (root == null)
    {
        return false;
    }
    else if (root.Value == value)
    {
        return true;
    }
    else if (root.Value < value)
    {
        return  Contains(root.Right, value);
    }
    else
    {
        return Contains(root.Left, value);
    }
}

答案 1 :(得分:2)

您似乎错过了status来电中的Contains作业:

status = Contains(root.Right, value);

status = Contains(root.Left, value);