java语言多叉树转化为二叉树_多叉树转换为二叉树算法

方法:将多叉树的第一个儿子结点作为二叉树的左结点,将其兄弟结点作为二叉树的右结点。

举例,如下图:

树的结构为:

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;

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值