[英]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?
[英]How to find a parent of a node in a Binary Tree?
我有一棵从普通树转换为二叉树的树:
B
/
A
\
D
/ \
/ I
/ /
C H
\ \
E L
\
G
/
F
这意味着:
等等。
现在,我必须编写以下方法:
public Position<E> parent(Position<E> v)
其中“ v”代表上述树中的字母之一,并且此方法需要找到其父代。
我已经为此苦苦挣扎了数小时。
根据您显示的内容:
算法是:
start from root
for every node v
every left-child is node v's child so add this child to node v childs list
every right-child is node v's parent's child(or parent of parent until it is a left-child of its parent, then the node you discovered is the child of left-child node's parent's child).
用于在实际树中查找节点父节点的伪代码:
enter node.
if node is left child
print its node->parent.
else
while node->parent is right child
node = node->parent
print node->parent.
我和你在做同样的作业
对于该解决方案,通用树中的父节点将是二进制树中的一个节点,该节点具有一个左子节点,并且该父节点的右子节点不等于我们的节点v(请参阅节点I)。
您可以对此进行处理:如果v的父级是左子级,则v的父级将是最后一个带有左子级的节点。 但是父级一定不能有一个合适的子级,因此,如果有一个正确的子级,则必须搜索最后一个节点的上级父级(请参阅节点I)。
希望这可以帮助
这很简单; 假设您的Node类无权访问父类,即
class Node{
Node left;
Node right;
int value;
}
您需要做的就是从根开始并以pre-order
遍历树。 如果遇到目标节点,则其父节点是从堆栈中弹出的最后两个元素之一(为什么?)
@See 深度优先搜索
在这种二叉树中,将子指针重新标记为children
(左子代)和sibling
(右子代)是最简单的,因为它们就是它们的代表。 由于没有父指针,因此当找到可能是父节点的节点时,必须在搜索将来的节点时将其传递。
我需要做很多假设,因为您提供的信息很少。
如果Position
是您的节点类型,而您想要的函数是Tree
成员,那么它将类似于:
private Position<E> parentImpl(Position<E> v, Position<E> node, Position<E> parent) {
if (node.equals(v)) {
return parent;
}
for (Position<E> child = v.children; child != null; child = child.sibling) {
Position<E> rtn = parentImpl(v, child, node); // current node is parent
if (rtn != null) {
return rtn;
}
}
return null;
}
现在,您想要的函数只需调用此函数即可。
public Position<E> parent(Position<E> v) {
return parentImpl(v, root, null); // Root has no parent.
}
当v根本不在树中以及它是树的根时,这将返回null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.