在二叉树结点的寻找父亲一般树转换结点、父亲、二叉树、一般树

2023-09-11 23:19:58 作者:不爱你,是一个宣誓。

我是用二叉树实现通用树,与一般的算法,一个节点的第一个儿子是左的和其他兄弟姐妹的第一个儿子的权利。

I am using the Binary Tree implementation of a General Tree, with the general algorithm that, the first son of a node is the "left" and any other siblings are the "right" of the first son.

我试图来回答,给定一个节点p,我怎么能找到节点p的父亲吗?

What I'm trying to answer is, given a node p, how can I find the father of node p?

下面是一个节点(我遍历使用非递归的方式,从而被访问和父属性)

Here is a node (I'm traversing using a non-recursive way, thus the visited and parent attributes)

struct node {
  std::string name;
  int sons;
  bool visited;
  node * first;
  node * next;
  node * parent;    
};

下面是一个例子:

GeneralTree

  A                   
 /|\       
B C D

GeneralTree的二叉树版本

  A
 /
B
 \
  C
   \
    D

所以B,C和D的父节点都是一个。

So the father node of B, C, and D are all A.

推荐答案

只要按照家长的联系,直到找到一个空引用 - 这种情况下,如果你开始与 P 是根节点 - 或者你是从它的左子传来的节点一个节点

Just follow the parent links until you find a null reference - this happens if you start with p being the root node - or a node with the node you are coming from as its left child.

var current = p;
var parent = current.parent;

while ((parent != null) && (current != parent.left))
{
    current = parent;
    parent = current.parent;
}

现在包含节点的父节点 P 如果 P 包含根节点。

Now parent contains the parent node of the node in p or null if pcontains the root node.