题
我写了这段代码
我有这些错误
无法在findmin上隐式转换类型x.Program.TreeNode'到'int'//
无法在findmax上隐式转换类型x.Program.TreeNode'到'int'//
并且是我的主要正确或遗失的东西吗?
以及我如何计算节点,离开并获得高度(只需要提示)
class Program
{
static void Main(string[] args)
{
BinarySearchTree t = new BinarySearchTree();
t.insert(ref t.root, 10);
t.insert(ref t.root, 5);
t.insert(ref t.root, 6);
t.insert(ref t.root, 17);
t.insert(ref t.root, 2);
t.insert(ref t.root, 3);
BinarySearchTree.print(t.root);
}
public class TreeNode
{
public int n;
public TreeNode _left;
public TreeNode _right;
public TreeNode(int n, TreeNode _left, TreeNode _right)
{
this.n = n;
this._left = _left;
this._right = _right;
}
public void DisplayNode()
{
Console.Write(n);
}
}
public class BinarySearchTree
{
public TreeNode root;
public BinarySearchTree()
{
root = null;
}
public void insert(ref TreeNode root, int x)
{
if (root == null)
{
root = new TreeNode(x, null, null);
}
else
if (x < root.n)
insert(ref root._left, x);
else
insert(ref root._right, x);
}
public int FindMin()
{
TreeNode current = root;
while (current._left != null)
current = current._left;
return current;
}
public int FindMax()
{
TreeNode current = root;
while (current._right != null)
current = current._right;
return current;
}
public TreeNode Find(int key)
{
TreeNode current = root;
while (current.n != key)
{
if (key < current.n)
current = current._left;
else
current = current._right;
if (current == null)
return null;
}
return current;
}
public void InOrder(ref TreeNode root)
{
if (root != null)
{
InOrder(ref root._left);
root.DisplayNode();
InOrder(ref root._right);
}
}
public static void print(TreeNode root)
{
if (root != null)
{
print(root._left);
Console.WriteLine(root.n.ToString());
print(root._right);
}
}
解决方案
既然你需要( FindMin
/ FindMax
)来返回 int
,你的意思是 current.n
?
更新:对于叶子和节点的计数,如何(作为 TreeNode
的实例方法):
public int CountNodes()
{
int count = 1; // me!
if (_left != null) count += _left.CountNodes();
if (_right != null) count += _right.CountNodes();
return count;
}
public int CountLeaves()
{
int count = (_left == null && _right == null) ? 1 : 0;
if (_left != null) count += _left.CountLeaves();
if (_right != null) count += _right.CountLeaves();
return count;
}
如果我错过了这一点,请告诉我......
其他提示
您的 FindMin()
和 FindMax()
方法正在尝试返回 TreeNode
对象,但签名表示它们返回 int 代码>秒。因为似乎没有在程序中使用这些方法,所以你可以删除它们吗?
不隶属于 StackOverflow