c++ - Left-Child Right-Sibling 将兄弟姐妹移动到子节点?
问题描述
例如,我有一个 Left-Child Right-Sibling 树:
例如,如果我想让 E(包括其子节点 E、K、L、P、Q)成为 H 节点的子节点。所以 H 将包含 N、O、E(及其子节点)我打算将子节点添加到父节点,然后删除旧节点,但随后会有新的父子节点对。最短的方法是什么?
这是一些要重现的代码:
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
struct Node
{
string data;
struct Node *next;
struct Node *child;
};
// Creating new Node
Node* newNode(string data)
{
Node *newNode = new Node;
newNode->next = newNode->child = NULL;
newNode->data = data;
return newNode;
}
// Adds a sibling to a list with starting with n
Node *addSibling(Node *n, string data)
{
if (n == NULL)
return NULL;
while (n->next)
n = n->next;
return (n->next = newNode(data));
}
// Add child Node to a Node
Node *addChild(Node * n, string data)
{
if (n == NULL)
return NULL;
// Check if child list is not empty.
if (n->child)
return addSibling(n->child, data);
else
return (n->child = newNode(data));
}
// Traverses tree in level order
void traverseTree(Node * root)
{
if (root == NULL)
return;
while (root)
{
cout << " " << root->data;
if (root->child)
traverseTree(root->child);
root = root->next;
}
}
//Driver code
int main()
{
Node *root = newNode("A");
Node *nB = addChild(root, "B");
Node *nC = addChild(root, "C");
Node *nD = addChild(root, "D");
Node *nE = addChild(root, "E");
Node *nF = addChild(root, "F");
Node *nG = addChild(root, "G");
Node *nH = addChild(nB, "H");
Node *nI = addChild(nB, "I");
Node *nJ = addChild(nB, "J");
Node *nK = addChild(nE, "K");
Node *nL = addChild(nE, "L");
Node *nM = addChild(nG, "M");
Node *nN = addChild(nH, "N");
Node *nO = addChild(nH, "O");
Node *nP = addChild(nK, "P");
Node *nQ = addChild(nL, "Q");
traverseTree(root);
return 0;
}
解决方案
推荐阅读
- php - AJAX 在 localhost 中有效,但在实时网络中无效
- css - CSS 倾斜的子菜单项显示不正确
- java - 将 Webdriver 实例从一个方法传递到 Selenium 中的另一个方法(在同一类中)
- android - 更新 Gradle 和构建工具后缺少 Android JAVA 字节码
- python - 在 sphinx 的 autodoc 中覆盖 __getitem__ 的默认签名
- c - 如何在 pc-lint 中定义实现特定 (XC8) 的 int 类型?
- google-sheets - 谷歌工作表,查询,来自单元格的数据范围
- node.js - 如何使用 multer-s3 处理错误
- elasticsearch - kibana目录下的控件可视化代码在哪里
- svn - 从 subclipse 中的存储库中删除修订(可能需要将主干与分支合并)