【发布时间】:2018-04-30 22:46:22
【问题描述】:
我正在尝试创建一个隐含泛型的二叉搜索树。在插入树的根后,我正在努力插入节点,很可能是我的插入逻辑错误。但我不知道怎么做。
我的问题是,我的插入逻辑有什么问题,因为我无法在根之后插入任何节点。
这是我的插入函数
public Node<T> insert(Node<T> node, T data) {
if (node == null)
{ System.out.println("1");
return new Node<T>(data);
}
if (node.getData().compareTo(data) < 0) {
node = new Node<T>(data, insert(node.getLeft(), data),node.getRight());
System.out.println("2");
node.setLeft(insert(node.getLeft(), data));
} else if (node.getData().compareTo(data) > 0) {
System.out.println("3");
node = new Node<T>(data, node.getLeft(), insert(node.getRight(), data));
node.setRight(insert(node.getRight(), data));
}
// After insert the new node, check and rebalance the current node if
// necessary.
switch (balanceNumber(node)) {
case 1:
node = rotateLeft(node);
break;
case -1:
node = rotateRight(node);
break;
default:
return node;
}
return node;
}
这就是我暗示它的地方
public void actionPerformed(ActionEvent e){
double x = Double.parseDouble(txtXCoord.getText());
double y = Double.parseDouble(txtYCoord.getText());
double m = Double.parseDouble(txtMass.getText());
String name = txtInput.getText();
switch(e.getActionCommand()){
case "add":
try {
tree.insert( drawPanel.tree.getRoot(), new Body(x,y,m,name));
drawPanel.setTree(tree);
//drawPanel.paint(getGraphics());
drawPanel.setVisible(true);
tree.PrintTree();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
我应该提到我有一个打印树的函数。
【问题讨论】:
-
您的问题是什么?问题是什么?代码不能编译吗?它会抛出一些
Exception吗?请更具体。 -
我的问题是,我的插入逻辑有什么问题,因为我无法在根之后插入任何节点。
-
好吧,对不起,我是一个 n00b 并且很着急。让问题变得更好
标签: java binary-tree