Given a pointer to the root of an N-ary tree, which has nodes with an extra pointer, gp (for grandparent), write a method that sets the grandparent of each node. Note that the root and its children’s grandparent should be null as they have none. void SetGrandparent(Node *root) { root->gp = nullptr; SetGrandparentHelper(root, nullptr); } void SetGrandparentHelper(Node *n, Node *parent) { if (!n) return; for (Node *c : n->children) { c->gp = parent; SetGrandparentHelper(c, n); } } |
Trees and Graphs >