我有一个整数数组,我需要使用二进制搜索树方法找到这个数组的最小值。我对BST不太自信,但我知道如何在BST中插入和搜索。
我应该执行哪些程序,以便获得最小值。 这是我写的伪代码。
我不知道我是在正确的道路上还是没有?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Collections;
namespace ConsoleApp2
{
class Program
{
public class Node
{
public int Data;
public Node Left;
public Node Right;
public void DisplayNode()
{
Console.Write(Data + " ");
}
}
public Node root;
public Program()
{
root = null;
}
public void Insert(int i)
{
Node newNode = new Node();
newNode.Data = i;
if (root == null)
root = newNode;
else
{
Node current = root;
Node parent;
while (true)
{
parent = current;
if (i < current.Data)
{
current = current.Left;
if (current == null)
{
parent.Left = newNode;
break;
}
else
{
current = current.Right;
if (current == null)
{
parent.Right = newNode;
break;
}
}
}
}
}
}
static void Main()
{
int minvalue(Node node)
{
Node current = node;
/* loop down to find the leftmost leaf */
while (current.Left != null)
{
current = current.Left;
}
return (current.Data);
}
Program nums = new Program();
nums.Insert(50);
nums.Insert(17);
nums.Insert(23);
nums.Insert(12);
nums.Insert(19);
Node root = null;
int min = minvalue(root);
Console.WriteLine(min);
Console.ReadLine();
}
}
}
这是我的解决方案,但我有错误 System.NullReferenceException:'对象引用未设置为对象的实例。' 当前为空。
答案 0 :(得分:0)
我修改了你的代码,所以它编译并且结构合理。我没有解决任何编码问题。你必须解决。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Collections;
namespace ConsoleApp2
{
class Program
{
static void Main()
{
Node nums = new Node();
nums.Insert(50);
nums.Insert(17);
nums.Insert(23);
nums.Insert(12);
nums.Insert(19);
int min = nums.MinValue(nums.root);
Console.WriteLine(min);
Console.ReadLine();
}
}
public class Node
{
public int Data;
public Node Left;
public Node Right;
public void DisplayNode()
{
Console.Write(Data + " ");
}
public Node root = null;
public int MinValue(Node node)
{
Node current = node;
/* loop down to find the leftmost leaf */
while (current.Left != null)
{
current = current.Left;
}
return (current.Data);
}
public void Insert(int i)
{
Node newNode = new Node();
newNode.Data = i;
if (root == null)
root = newNode;
else
{
Node current = root;
Node parent;
while (true)
{
parent = current;
if (i < current.Data)
{
current = current.Left;
if (current == null)
{
parent.Left = newNode;
break;
}
else
{
current = current.Right;
if (current == null)
{
parent.Right = newNode;
break;
}
}
}
}
}
}
}
}