![](/img/trans.png)
[英]Java - finding a parent of a node in a Binary Tree? (converted from a general tree)
[英]After a General Tree is converted to a Binary Tree, how is it possible to find the parent given a node “v” of the General Tree using the Binary Tree?
我尝试了两种实现方式,但它们效果不佳。
这是我完全坚持的实现之一。
/** Returns the parent of a given node or the node itself if it is the root */
public Position<E> parent(Position<E> v) throws IllegalArgumentException {
if(bTree.isRoot(v)) { return v; } // returns the node v itself if v is the root.
Position<E> parent = bTree.root();
// execute this recursive method and return the parent.
return preorderTraversal(parent, v, null);
}
/* This is the helper method that will traverse the binary tree in PreOrder. It updates
* the parent until the node v has been found.
*/
private Position<E> preorderTraversal(Position<E> focusNode, Position<E> v, Position<E> parent) {
System.out.print(focusNode.getElement() + "\t");
if (focusNode != null && v != focusNode && hasLeft(focusNode)) {
parent = focusNode;
System.out.print("setting parent to: " + parent.getElement() + "\t");
preorderTraversal(bTree.left(focusNode), v, parent);
}
else if (focusNode != null && v != focusNode && hasRight(focusNode)){
preorderTraversal(bTree.right(focusNode), v, parent);
}
return parent;
}
// -------------- EXTRA HELPER METHODS ---------------
private boolean hasLeft(Position<E> temp ) {
if (bTree.left(temp) != null) return true;
else return false;
}
private boolean hasRight(Position<E> temp ) {
if (bTree.right(temp) != null) return true;
else return false;
}
这里的问题似乎是它遍历左子树并更新正确的父级,但是在返回值时,它总是返回根节点。 我似乎不明白为什么会这样。 另一个是遍历正确的子树时,我的父节点总是错误的。 请帮忙!
您在没有动机的情况下对左右有所不同。 您尚未指定通用树是什么(猜测每个节点可以具有两个以上的后代 ,但是,由于转换后的节点似乎具有可比性:原始节点具有多少值?如何将其转换为a二叉树(左边的引用是后代引用,右边的用于兄弟姐妹?)提供URL可能是适当的。
合并检查: if (null == focusNode || v == focusNode) return parent;
。
不要像在parent
重复之前那样给变量preorderTraversal(bTree.left(focusNode), v, focusNode);
一个与其有意义的名称相矛盾的值,而preorderTraversal(bTree.left(focusNode), v, focusNode);
传递左值,而是传递适当的值: preorderTraversal(bTree.left(focusNode), v, focusNode);
。
如果您在条件陈述的不同部分进行不同的处理而没有无可争辩且显而易见的理由 ,请发表评论:为什么在正确地重复发生时您要通过父母?
(一个引用方法注释的方法。考虑将其升级为javadoc 。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.