我正在尝试实现一个基本的二叉搜索树。
我能够创建一个 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/