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

时间:2013-11-15 07:20:56

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

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

我能够创建一个Node,但AddNode()函数存在问题。它应该向现有树添加一个新节点,但它replaces

任何想法应该在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);
    }
}

感谢。

2 个答案:

答案 0 :(得分:4)

这些行替换了根目录:

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

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

你也可以删除this量词 - 只有当你有一个同名的局部变量或者其他一些极端情况时才需要它们。

添加辅助函数很有用/必要,因为必须单独为root提供帮助。

更新的代码:

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

答案 1 :(得分:1)

此语句仅在您第一次运行代码时才会生效。

if (this.root == null)
{
    this.root = new Node(valueToBeInserted);
}

this.root再也没有设置为null ... 通常你会像这样编码添加:

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

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

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