多叉树转换为二叉树算法。算法描述:将多叉树的第一个儿子结点作为二叉树的左结点,将其兄弟结点作为二叉树的右结点。
举例,如下图:
树的结构为:
typedef struct BinaryTreeNode{
struct BinaryTreeNode* leftChild;
struct BinaryTreeNode* rightChild;
int value;
};
typedef struct TreeNode{
struct TreeNode* child[];
int child_count;
int value;
};
BinaryTreeNode* ToBinaryTree(TreeNode*root){
if(root == null) return null;
BinaryTreeNode* binaryRoot = new BinaryTreeNode();
binaryRoot->leftChild = binaryRoot->rightChild = NULL;//注意初始化
binaryRoot->value = root->value;
binaryRoot->leftChild = ToBinaryTree(root->child[0]);
BinaryTreeNode* brother = binaryRoot->leftChild;
for(int i = 1; i < root->child_count;i++){
brother->rightChild = ToBinaryTree(root->child[i]);
brother = brother->rightChild;
}
return binaryRoot;
}
树采用的存储结构见表一,转化为二叉树见表二,之后再将表转化为二叉链表的存储方式,程序及相应测试见代码:
|
|
表一 表二
#include<iostream>
#include <string>
using namespace std;
struct Node // 以表的形式存储的树结点
{
chardata;
intparent;
intlchild;
intrchild;
};
struct TreeNode // 以二叉链表存储的树结点
{
chardata;
TreeNode*l;
TreeNode*r;
};
// 创建树的表并转化为二叉树
int creattable(Node table[])
{
intn, k, i, j;
cout<< “输入结点个数(<20):”;
cin>> n;
if(n > 0)
{
cout << “输入结点信息和双亲编号(第一个请输入根结点信息如a-1 ):” << endl;
for (i = 0; i < n; i++)
{
cin >> table[i].data >> table[i].parent;
table[i].lchild = table[i].rchild = 0;
}
for (i = 0; i < n; i++)
{
for (j = 1; j < n; j++)
{
if (table[j].parent == i)
{
if (table[i].lchild == 0)
{
table[i].lchild = j;
k = j;
}
else
{
table[k].rchild = j;
k = j;
}
}
}
}
for (i = 0; i < n; i++)
{
cout << table[i].data << table[i].parent <<table[i].lchild << table[i].rchild << endl;
}
}
returnn;
}
// 将表转化为二叉链表
void Build(TreeNode *¤t, Nodenode[], int pos, int n)
{
if(n > 0)
{
if (current == 0)
{
current = new TreeNode;
current->l = current->r = 0;
}
current->data = node[pos].data;
if (node[pos].lchild)
Build(current->l, node, node[pos].lchild, n);
if (node[pos].rchild)
Build(current->r, node, node[pos].rchild, n);
}
}
// 访问结点
void Visit(TreeNode *current)
{
cout<<current->data<<“”;
}
// 按先序遍历
void Preorder(TreeNode *root)
{
TreeNode *current = root;
if(current != 0)
{
Visit(current);
Preorder(current->l);
Preorder(current->r);
}
}
int main()
{
Nodenode[20];
intn = creattable(node);
TreeNode*root = 0;
Build(root,node, 0, n);
if(root)
{
cout << “先序遍历:”;
Preorder(root);
cout << endl;
}
else
{
cout << “空树!” << endl;
}
return0;
}