现在的位置: 首页 > 综合 > 正文

多叉树转二叉树

2013年08月28日 ⁄ 综合 ⁄ 共 2136字 ⁄ 字号 评论关闭

多叉树的根结点为二叉树的根,多叉树的结点的第一个儿子变成二叉树对应结点的左孩子,多叉树的结点的右兄弟变成二叉树种该结点的右孩子。代码如下:

C语言:
01 #include <stdio.h>
02 #include <sys/time.h>
03 #include <limits.h>
04 #include <stdlib.h>
05
06 typedef struct   TreeNode{  
07     int   child_count;  
08     int   value;  
09     struct   TreeNode*   child[0];
10 } TreeNode_t;
11
12 typedef struct   BinaryTreeNode{  
13     struct   BinaryTreeNode*   leftChild;  
14     struct   BinaryTreeNode*   rightChild;  
15     int   value;  
16 } BinaryTreeNode_t;
17
18 BinaryTreeNode_t* ToBinaryTree(TreeNode_t* root){  
19     if(root == NULL) {    
20         return   NULL;  
21     }
22
23     BinaryTreeNode_t* binaryRoot = (BinaryTreeNode_t*)malloc(sizeof(BinaryTreeNode_t));  
24     binaryRoot->value = root->value;  
25     binaryRoot->leftChild = ToBinaryTree(root->child[0]);  
26
27     BinaryTreeNode_t* brother = binaryRoot->leftChild;
28     int i
29     for(i = 1; i < root->child_count;i++){  
30          brother->rightChild = ToBinaryTree(root->child[i]);  
31          brother = brother->rightChild;  
32     }  
33     return binaryRoot;  
34 }
35   
36 TreeNode_t* Tn;/*多叉树的根*/
37 BinaryTreeNode_t* Bn;/*二叉树的根*/
38
39 int main (int argc, char *argv[])
40 {
41     /*构造一棵简单的多叉树,用于测试*/
42     Tn = (TreeNode_t*)malloc(40);
43     TreeNode_t* t[5];
44     memset(t,0,sizeof(t));
45
46     TreeNode_t* tmp;
47     TreeNode_t* tmp1;
48     TreeNode_t* tmp2;
49     TreeNode_t* tmp3;
50     TreeNode_t* tmp4;
51     TreeNode_t* tmp5;
52
53     tmp = (TreeNode_t*)malloc(sizeof(TreeNode_t) + sizeof(TreeNode_t*) * 5 );
54     tmp->value = 'b';
55     tmp->child_count = 3;
56     tmp1 = (TreeNode_t*)malloc(40);
57     tmp1->value = 'c';
58     tmp2 = (TreeNode_t*)malloc(40);
59     tmp2->value = 'd';
60
61     tmp3 = (TreeNode_t*)malloc(40);
62     tmp3->value = 'e';
63     tmp4 = (TreeNode_t*)malloc(40);
64     tmp4->value = 'f';
65     tmp5 = (TreeNode_t*)malloc(40);
66     tmp5->value = 'g';
67
68     tmp->child[0] = tmp3;
69     tmp->child[1] = tmp4;
70     tmp->child[2] = tmp5;
71     for(i = 0;i<tmp->child_count;i++) {
72         printf("%c/r/n",tmp->child[i]->value);
73     }
74
75     Tn->value = 'a';
76     Tn->child_count = 3;
77     memset(t,0,sizeof(t));
78     t[0] = tmp;
79     t[1] = tmp1;
80     t[2] = tmp2;
81     memcpy(Tn->child,t,sizeof(t));
82    
83     /*转化为二叉树*/
84     Bn = ToBinaryTree(Tn);
85
86     return(0);
87 }

 结果就懒得写输出了,debug下看Bn这个指针就ok了。

ps:代码用的代码发芽网http://fayaa.com/code转的html,还不错。

抱歉!评论已关闭.