【发布时间】:2019-03-28 07:20:18
【问题描述】:
我目前正在尝试编写方法来检查两个不同的二叉搜索树中的所有节点,并在两个树之间找到具有公共键的节点。 (即尝试从树 1 和树 2 中查找包含相同键的节点。如果找到公共节点,则该方法返回 true,否则返回 false。第二棵树存储在与树不同的对象中1,叫GraphicalObject。关键是坐标的形式,大小比较是按列顺序完成的。
我已经编写了以下代码,但想知道它是否有什么问题,或者有什么可以改进的地方?
1) 一种使用递归调用检查树 1 中的节点是否与树 2 中的每个节点相同的方法。 compareTo 方法在其他地方定义。
public boolean findPixel(BinaryNode node1, BinaryNode node2, GraphicalObject gobj) {
//Creating the final coordinate key by altering the original key in nodes of tree 2.
int xCor = node2.getData().getLocation().xCoord() + gobj.getOffset().xCoord() - graphicPos.xCoord();
int yCor = node2.getData().getLocation().yCoord() + gobj.getOffset().yCoord() - graphicPos.yCoord();
Location newLoc = new Location(xCor, yCor); //Creates the final key to be checked up on
if(node1.getData().getLocation().compareTo(newLoc) == 0) { //If keys are the same
return true;
} else {
if(node1.getData().getLocation().compareTo(newLoc) == -1) { //if key from node 1 is smaller than key from node 2.
node2 = node2.getLeft();
findPixel(node1, node2, gobj);
} else {
node2 = node2.getRight();
findPixel(node1, node2, gobj);
}
}
return false;
}
2) 使用findPixel 方法检查树 1 中的每个节点并将它们与树 2 中的每个节点进行比较的方法,使用中序遍历。
private boolean findCommonNode(BinaryNode node1, BinaryNode node2, GraphicalObject gobj) {
if(node1 != null) {
findCommonNode(node1.getLeft(), node2, gobj);
return findPixel(node1, node2, gobj);
findCommonNode(node1.getRight(), node2, gobj);
}
}
3) 如果找到两棵树之间的公共节点,则返回 true,否则返回 false。
public boolean intersects(GraphicalObject gobj){
BinaryNode tempNode = newTree.getRoot();
BinaryNode tempNode2 = gobj.getTree().getRoot();
if (findCommonNode(tempNode, tempNode2, gobj) == true) {
return true;
} else {
return false;
}
}
这段代码有什么问题吗?或者我可以做些什么来让它变得更好或更高效地运行?
【问题讨论】:
-
也许你想做
return findPixel(node1, node2, gobj);// etc -
您的意思是在第一种方法中使用 else 和 if 语句? :) 另外,在按顺序遍历的第二种方法中,return 语句可以放在那里吗?我不确定这是否可行。
-
对不起,我说的是第一种方法(我读起来很无聊)——试试看它是否有效
-
我觉得有点用。这实际上是制作游戏的类作业的一部分,如果找到一个公共节点,屏幕上的两个图形图标将相互重叠,这不是我们想要的。现在,它有时不会重叠(这很好),但很多时候,即使没有公共节点,它仍然会重叠(意味着这些方法没有正确检测到公共节点)。我不确定出了什么问题,我一步一步地检查了代码以弄清楚它是如何工作的,看起来还不错? ://
标签: java recursion tree binary-search-tree nodes