【发布时间】:2013-11-15 07:20:55
【问题描述】:
我正在尝试实现一个基本的二叉搜索树。
我能够创建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);
}
}
谢谢。
【问题讨论】:
-
写
public int value { get; set; }而不是public int value;有什么意义? -
@PaulDraper:是的,没有特殊情况。谢谢你提出来。但是,你知道我应该如何为
AddNode编写函数吗?
标签: c# .net data-structures tree binary-search-tree