c# - 二叉搜索树的递归函数实现

标签 c# .net data-structures tree binary-search-tree

我正在尝试实现一个基本的二叉搜索树。

我能够创建一个 Node,但我在使用 AddNode() 函数时遇到了问题。它应该向现有树中添加一个新节点,但它替换了它。

知道应该在 AddNode() 函数中做什么吗?

class Node
{
    public int value { get; set; }

    public Node left { get; set; }

    public Node right { get; set; }

    public Node(int i)
    {
        this.value = i;
        this.left = null;
        this.right = null;
    }

}

class Tree
{
    public Node root { get; set; }

    public Tree(Node n)
    {
        root = n;
    }

    public void AddNode(int valueToBeInserted)
    {
        if (this.root == null)
        {
            this.root = new Node(valueToBeInserted); 
            // problem here : existing tree is destroyed. 
            // a new one is created. 
            // instead it should add a new node to the end of the tree if its null
        }

        if (valueToBeInserted < this.root.value)
        {
            this.root = this.root.left;
            this.AddNode(valueToBeInserted);
        }

        if (valueToBeInserted > this.root.value)
        {
            this.root = this.root.right;
            this.AddNode(valueToBeInserted);
        }
    }

    public void printTree()
    {
        // print recursively the values here.
    }
}

class TreeTest
{
    public void Test()
    {
        var tree = new Tree(new Node(100));
        tree.AddNode(20);
        tree.AddNode(100);
    }
}

谢谢。

最佳答案

这些行替换根:

this.root = this.root.left;
this.root = this.root.right;

您应该将参数传递给您的递归函数。

您还可以删除 this 量词 - 它们仅在您有一个具有相同名称的局部变量或可能在其他一些极端情况下才需要。

添加辅助函数是有用的/必要的,因为必须单独满足根的需求。

更新代码:

public void AddNode(int valueToBeInserted)
{
    if (root == null)
    {
        root = new Node(valueToBeInserted);
    }
    else
    {
        AddNode(valueToBeInserted, root);
    }
}

private void AddNode(int valueToBeInserted, Node current)
{
    if (valueToBeInserted < current.value)
    {
        if (current.left == null)
            current.left = new Node(valueToBeInserted);
        else
            AddNode(valueToBeInserted, current.left);
    }

    if (valueToBeInserted > current.value)
    {
        if (current.right == null)
            current.right = new Node(valueToBeInserted);
        else
            AddNode(valueToBeInserted, current.right);
    }
}

关于c# - 二叉搜索树的递归函数实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19995607/

相关文章:

c# - 如何在 C# 中使用线程读取和解析非常大的平面文件?

.net - Windows Azure,解决实例和粘性 session

c# - 如何在 ASP.NET 4.5 中访问 web.config 配置文件属性?

algorithm - 什么数据结构可以有效地减少哈希表桶中的锁定成本?

c# - Socket 的扩展方法内存泄漏 'ReceiveAsync' !

c# - 如何验证调用方法时是否引发了操作(使用 Moq 进行单元测试)

C编程: Linked Lists

c++ - 允许 key 增加的可变优先级队列

c# - ASP.NET MVC 路由 : bypass staticfile handler for path

c# - StructureMap 2.5 和内部实现者