方法:将多叉树的第一个儿子结点作为二叉树的左结点,将其兄弟结点作为二叉树的右结点。
举例,如下图:
树的结构为:
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;
}
看是什么二叉树了。
先遍历多叉树,将所有节点得到,然后根据相应的二叉树的规则构造二叉树就行了。
树采用的存储结构见表一,转化为二叉树见表二,之后再将表转化为二叉链表的存储方式,程序及相应测试见代码:
data
parent
0
A
-1
1
B
0
2
C
0
3
D
0
4
E
1
5
F
1
6
G
3
data
parent
leftchild
rightchild
0
A
-1
1(原值为0 )
0
1
B
0
4
2
2
C
0
0
3
3
D
0
6
0
4
E
1
0
5
5
F
1
0
0
6
G
3
0
0
#include
#include
using namespace std ;
struct Node { //以表的形式存储的树结点
char data;
int parent;
int lchild;
int rchild;
};
struct TreeNode { //以二叉链表存储的树的结点
char data;
TreeNode* l;
TreeNode* r;
};
int creattable( Node table[]){ //创建树的表并转化为二叉树
int n,k,i,j;
cout<
cin>>n;
if ( n>0 ){
cout<
a -1 ):"<
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<
[i].lchild<
}
return n;
}
void Build ( TreeNode*&
current,Node node[], 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(
urrent->r ,node, node[pos].rchild, n);
}
}
void Visit ( TreeNode* current ){ //访问结点
cout<data<
";
}
void Preorder( TreeNode* root ){ //按先序遍历
TreeNode* current =
root;
if( current != 0
){ Visit(
current );
Preorder(
current->l );
Preorder(
current->r
); }
}
int main(){
Node node [20];
int n = creattable( node );
TreeNode* root = 0;
Build ( root, node, 0 , n);
if (root){
cout<
Preorder ( root );
cout<
}
else
cout<
return 1;
}