我想使用下一个数组创建一个树:
int numbers[] = {4,6,7,23,60};
这个想法是数字总和为100。
我想使用下一种格式在树中订购此列表:
1.如果treeLeafNode空间不存在,请创建它。
3.使用父节点修改列表,现在有(10,7,23,60)
从您现在的低数字排序(7,10,23,60)
重新执行步骤1,2,3,4,直至到达顶部',即(LeftChildNode:40,ParentNode:100,RightChildNode:60);
< / LI> 醇>问题:从现在的工具中,创建树的最简单方法是什么?
这是我到目前为止所做的事情。
我有这个功能:修剪,从低到高排序。 问题:我的树创建功能如下......但是达到了分段错误:
void insert_Leaf(int L,int R, hojaNodo **leaf)
{
//JiCase
if(L+R >= 101)
return;
hojaNodo *tempLeafMain;
tempLeafMain = (hojaNodo*)malloc(sizeof(hojaNodo));
tempLeafMain = *leaf;
hojaNodo *tempLeafLeft;
tempLeafLeft = (hojaNodo*)malloc(sizeof(hojaNodo));
int tempLeft = L;
int tempRight = R;
int tempParent = tempLeft + tempRight;
//Creamos Parent
if(tempLeafMain == 0)
{
hojaNodo *tempLeafRight;
tempLeafRight = (hojaNodo*)malloc(sizeof(hojaNodo));
tempLeafMain->probabilidad = tempParent;
// init los hijos a null
tempLeafMain->left = tempLeafLeft;
tempLeafMain->right = tempLeafRight;
tempLeafLeft ->probabilidad = tempLeft;
tempLeafRight->probabilidad = tempRight;
return;
}//eof check doesnt exist
else if(tempLeafMain != NULL){
if(tempLeft < tempLeafMain->probabilidad){
hojaNodo *tempLeafParent;
tempLeafParent = (hojaNodo*)malloc(sizeof(hojaNodo));
tempLeafParent->probabilidad = tempLeft + tempLeafMain->probabilidad;
tempLeafParent->right = tempLeafMain;
tempLeafParent->left = tempLeafLeft;
tempLeafLeft->probabilidad = tempLeft;
//tempLeaf->right = *leaf;
*leaf = tempLeafParent;
}//eof if
}//elseif
}//eof insertLeaf
感谢您的时间,如果可能的话,感谢您的帮助。 祝你有个美好的一天!
答案 0 :(得分:1)
这是解决分段错误后代码的样子。
void insert_Leaf(int L,int R, hojaNodo **leaf)
{
//JiCase
printf("inside insert_leaf\n");
if(L+R >= 101)
return;
hojaNodo *tempLeafHead;
tempLeafHead = (hojaNodo*)malloc(sizeof(hojaNodo));
tempLeafHead = *leaf;
int tempLeft = L;
int tempRight = R;
int tempParent = tempLeft + tempRight;
//Creamos Parent
if(tempLeafHead == 0)
{
printf("head is null\n");
tempLeafHead = (hojaNodo*)malloc(sizeof(hojaNodo));
hojaNodo *tempLeafLeftChild;
tempLeafLeftChild = (hojaNodo*)malloc(sizeof(hojaNodo));
hojaNodo *tempLeafRightChild;
tempLeafRightChild = (hojaNodo*)malloc(sizeof(hojaNodo));
tempLeafHead->probabilidad = tempLeft + tempRight;
tempLeafHead->left = tempLeafLeftChild;
tempLeafHead->right = tempLeafRightChild;
tempLeafLeftChild->probabilidad = tempLeft;
tempLeafRightChild->probabilidad = tempRight;
*leaf = tempLeafHead;
return;
} else if(tempLeafHead != NULL){
printf("head is NOT null\n");
if(tempLeft < tempLeafHead->probabilidad){
hojaNodo *tempLeafParent;
tempLeafParent = (hojaNodo*)malloc(sizeof(hojaNodo));
hojaNodo *tempLeafLeftChild;
tempLeafLeftChild = (hojaNodo*)malloc(sizeof(hojaNodo));
tempLeafParent->probabilidad = tempLeft + tempLeafHead->probabilidad;
tempLeafParent->right = tempLeafHead;
tempLeafParent->left = tempLeafLeftChild;
tempLeafLeftChild->probabilidad = tempLeft;
//tempLeaf->right = *leaf;
*leaf = tempLeafParent;
}//eof if
}//elseif
}//eof insertLeaf