如何在树形结构中从Child移动到Parent?

时间:2022-12-20 21:35:26
struct node
{
    int data;
    node *child;
    node *sibling
};

I want to have a loop that moves from child to parent. If the root of a tree has 5 children then starts from last child to root. meaning that the loop should move in a reverse way.

我希望有一个从子节点移动到父节点的循环。如果树的根有5个子节点,则从最后一个子节点开始到根节点。意味着循环应该以相反的方式移动。

In fact, it could be easy if I have an array of children, but what if I just have a child parent relationship, in that case, each child has a parent, So is it possible that I go from child to parents until I get to root.

事实上,如果我有一系列的孩子,这可能很容易,但如果我只有一个孩子的父母关系怎么办,那么每个孩子都有一个父母,所以我有可能从孩子到父母,直到我得到根。

1 个解决方案

#1


2  

You need a parent pointer to move directly from child to parent in a loop. I find this works.

您需要父指针在循环中直接从子节点移动到父节点。我觉得这很有效。

struct node{
    int value;
    node * parent;
    node ** childArray;
    int NumberOfChildren;
}

You set parent to null on the root node, and set the childArray pointer to null on the leaf (final) node.

您在根节点上将parent设置为null,并在叶(最终)节点上将childArray指针设置为null。

When you want to move through the tree you use a node*.

当您想要在树中移动时,您使用节点*。

e.g.

例如

node * PCurrentNode = &MyNode;
PCurrentNode = MyNode->Parent;//Move Up
PCurrentNode = MyNode->ChildNodes[5]//Move to the 5th child node

You can avoid using parent pointers if you start at the root node and recurse down as you simply recurse up to get to the parent node.

如果从根节点开始并且只是递归到达父节点,则可以避免使用父指针。

#1


2  

You need a parent pointer to move directly from child to parent in a loop. I find this works.

您需要父指针在循环中直接从子节点移动到父节点。我觉得这很有效。

struct node{
    int value;
    node * parent;
    node ** childArray;
    int NumberOfChildren;
}

You set parent to null on the root node, and set the childArray pointer to null on the leaf (final) node.

您在根节点上将parent设置为null,并在叶(最终)节点上将childArray指针设置为null。

When you want to move through the tree you use a node*.

当您想要在树中移动时,您使用节点*。

e.g.

例如

node * PCurrentNode = &MyNode;
PCurrentNode = MyNode->Parent;//Move Up
PCurrentNode = MyNode->ChildNodes[5]//Move to the 5th child node

You can avoid using parent pointers if you start at the root node and recurse down as you simply recurse up to get to the parent node.

如果从根节点开始并且只是递归到达父节点,则可以避免使用父指针。