用Java显示二进制搜索树
我在显示二进制搜索树时遇到问题 我希望能够看到插入到树中的每个值,但我不确定错误位于何处。还有什么我应该改变的,使这段代码更实用或更容易阅读用Java显示二进制搜索树,java,binary-search-tree,Java,Binary Search Tree,我在显示二进制搜索树时遇到问题 我希望能够看到插入到树中的每个值,但我不确定错误位于何处。还有什么我应该改变的,使这段代码更实用或更容易阅读 class BSTNode { public int value; // data item (key) public BSTNode leftChild; // this node's left child public BSTNode rightChild; // this node's right child pub
class BSTNode {
public int value; // data item (key)
public BSTNode leftChild; // this node's left child
public BSTNode rightChild; // this node's right child
public void displayNode() // display this node
{
StringBuilder node = new StringBuilder();
node.append("{");
node.append(value);
node.append("}");
System.out.println(node);
}
}
class BSTree {
private BSTNode root; // first node of tree
public BSTree() {
root = null;
}
public BSTNode find(int searchValue) // looks for node with certain key
{
BSTNode current = root;
while (current.value != searchValue) {
if (searchValue < current.value)
current = current.leftChild;
else
current = current.rightChild;
if (current == null)
return null;
}
return current;
}
public void insert(int value) // insert a new Node
{
BSTNode newNode = new BSTNode();
BSTNode current, parent;
newNode.value = value;
if (root == null)
root = newNode;
else {
current = root;
while (true) {
parent = current;
if (value < current.value) // go left
{
current = current.leftChild;
if (current == null) // if end of line
{
parent.leftChild = newNode;
return;
}
} // end left
else // go right
{
current = current.rightChild;
if (current == null) // if end of the line
{
parent.leftChild = newNode;
return;
}
}
}
}
}
目前输出为
23
49 --
我猜这是一个复制粘贴错误:
else // go right
{
current = current.rightChild;
if (current == null) // if end of the line
{
parent.leftChild = newNode;
return;
}
}
应该是:
else // go right
{
current = current.rightChild;
if (current == null) // if end of the line
{
parent.rightChild = newNode;
return;
}
}
每次找到合适的右节点时,您都会覆盖左节点,这就是为什么您只能看到添加的第一个节点(23)和最后一个节点(49),它们应该位于右侧,但似乎位于左侧。在您的
insert
方法中遍历树时,您不小心向左走,而不是向右走:
else // go right
{
current = current.rightChild;
if (current == null) // if end of the line
{
parent.leftChild = newNode;
return;
}
}
要修复此问题,请将parent.leftChild
的引用更改为parent.righchild
此外,还可以对代码进行改进。例如,使用BSTNode
类的参数创建一个构造函数,这样就不必每次都设置.value
。像这样:
class BSTNode {
//constructor
public BSTNode(int value){
this.value = value;
}
}
然后换成
BSTNode newNode=新的BSTNode(值)代码>插入中的else条件将节点添加到leftChild而不是rightChild
else // go right
{
current = current.rightChild;
if (current == null) // if end of the line
{
parent.leftChild = newNode;
return;
}
}
在您确定需要调整间距后,所有空值上的空格都已用完,因此数字开始合并在一起。您是否考虑过将其表示为JTree中的节点?或者只需要使用System.out.print()将此文件打印到屏幕上吗?
class BSTNode {
//constructor
public BSTNode(int value){
this.value = value;
}
}
else // go right
{
current = current.rightChild;
if (current == null) // if end of the line
{
parent.leftChild = newNode;
return;
}
}