[英]Inserting in a Complete Binary Tree
我正在嘗試為學校作業插入一個完整的二叉樹。 我的樹的結構是這樣的
typedef struct TreeNode {
void * data;
struct TreeNode * left;
struct TreeNode * right;
struct TreeNode * parent;
} TNode;
typedef struct CompleteBinaryTree {
TNode * root;
TNode * last;
int numelm;
} CBTree;
根據情況,我有 4 種插入方式
我目前被困在我的第三種方式上,我不知道我的代碼有什么問題。
有人能把我推向正確的方向嗎?
謝謝 !
void CBTreeInsert(CBTree* tree, void* data) {
TNode * tmp = newTNode(data);
TNode * curr = tree->last;
if(tree->root == NULL) //empty
{
tree->root = tmp;
}
else if(tree->last == tree->root) //one node
{
tree->last->left = tmp;
}
else if(tree->last->parent->right == NULL) //general
{
tree->last->parent->right = tmp;
}
else if(tree->last->parent == tree->last->parent->right) //degenarated
{
while(curr->parent == curr->parent->right)
curr = curr->parent;
if(curr != tree->root)
{
curr = curr->parent->right;
while(curr->left != NULL)
curr = curr->left;
}
curr->left = tmp;
}
else
{
while(curr->left != NULL)
curr = curr->left;
curr->left = tmp;
}
}
else
{
fprintf(stderr,"Error\n");
}
tree->last = tmp;
tree->numelm++;
}
我想你或多或少有它,但是:
我沒有看到新節點的tmp->parent
設置在哪里?
else if(tree->last->parent == tree->last->parent->right)
壞了,我覺得這應該是else if(tree->last == tree->last->parent->right)
,在這一點上這絕對是正確的。
while(curr->parent == curr->parent->right) curr = curr->parent;
curr == tree->root
可能有問題,盡管可以通過設置tree->root->parent = tree->root
你有兩份:
while(curr->left != NULL)
{
curr = curr->left;
}
curr->left = tmp;`
我很想這樣做:
else if (tree->last == tree->last->parent->right)
{
TNode * curr = tree->last->parent ; // NB: know that tree->last != tree->root
// so can step up.
while (1)
{
if (curr == tree->root)
break ;
if (curr == curr->parent->left)
{
// The parent of the curr node is to the right of the last node, so
// step to its right, and then insert to the extreme left of that.
curr = curr->parent->right ;
assert(curr != NULL) ;
break ;
} ;
curr = curr->parent ;
} ;
// Arrive here with curr as root of sub-tree in which now want to insert the
// new node as the left-most child.
while (curr->left != NULL)
{
assert(curr->right != NULL) ;
curr = curr->left ;
} ;
assert(curr->right == NULL) ;
tmp->parent = curr ;
curr->left = tree->last = tmp;
}
但我沒有測試過這個。 (還有其他地方需要設置tmp->parent
。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.