我正在测试,以确保我可以打印出我的二进制搜索树,用于我班级中的项目。我有它,所以建立一个字符串表达式,从那里,程序将字符串拆分为一个数组,并将每个元素插入根节点。我已经调试了程序,它似乎正确地插入了节点,但最后,当程序停止循环时,根节点将最终为空,并且不允许我打印二叉树。
为什么我的根节点返回null?我尝试查看该程序,但我找不到错误
节点类
public class Node<T>
{
private T value;
Node left;
Node right;
public Node(T value)
{
this.value=value;
left=null;
right=null;
}
public String toString()
{
return value.toString();
}
public T getValue()
{
return value;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
public void setValue(T value) {
this.value = value;
}
}
二进制搜索树类
import java.io.*;
import java.util.*;
public class binarySearchTree<T extends Comparable<T>>
{
private Node<T> root;
public binarySearchTree()
{
root=null;
}
public Node<T> buildTree(String expression)
{
String[] expressionSplit=expression.split("\\s{1,}");
binarySearchTree<String> stringBST=new binarySearchTree<String>();
for(int i=0;i<expressionSplit.length;i++)
{
stringBST.insert(expressionSplit[i]);
}
return root;
}
public Node<T> insertHelper(Node<T> p, T data)
{
if(p==null)
{
return new Node<T>(data);
}
int test=data.compareTo(p.getValue());
if(test==0)
{
return p;
}
if(test<0)
{
p.left=insertHelper(p.left,data);
}
else if(test>0)
{
p.right=insertHelper(p.right,data);
}
return p;
}
public void insert(T data)
{
root=insertHelper(root,data);
}
public static String inorder(Node<String> rootString)
{
if(rootString!=null)
{
return inorder(rootString.getLeft())+rootString.getValue()+" "+inorder(rootString.getRight());
}
return "";
}
public static void main(String[] args)
{
String expression="10 8 17 4";
binarySearchTree<String>test=new binarySearchTree<String>();
Node<String> root=test.buildTree(expression);
System.out.println(test.inorder(root));
}
}
答案 0 :(得分:0)
您基本上返回在root
方法中声明的buildTree
对象,该对象始终为null。
要解决此问题,请从该方法中删除Node<T> root = null;
。
此外,您正在使用BinarySearchTree
方法创建新的buildTree
对象。因此,更新的root
对象是该对象中的对象。
root
方法中BinarySearchTree
的原始main
对象永远不会更新,并且始终为空。
将您的buildTree
方法更改为这样。
public Node<T> buildTree(String expression)
{
T[] expressionSplit = (T[]) expression.split("\\s{1,}");
for (int i = 0; i < expressionSplit.length; i++)
{
insert(expressionSplit[i]);
}
return root;
}
答案 1 :(得分:0)
WITH StartTime AS (
SELECT
TimeStamp
, ROW_NUMBER() PARTITION BY (ORDER BY TimeStamp) RowNum
FROM
<<table>>
WHERE
TimeCode = 1
), StopTime AS (
SELECT
TimeStamp
, ROW_NUMBER() PARTITION BY (ORDER BY TimeStamp) RowNum
FROM
<<table>>
WHERE
TimeCode = 2
)
SELECT
SUM (DATEDIFF( MINUTE, StartTime.TimeStamp, StopTime.TimeStamp )) As TotalTime
FROM
StartTime
JOIN StopTime ON StartTime.RowNum = StopTime.RowNum