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