struct node {
int data;
struct node* left;
struct node* right;
};
挿入するノードを作成する関数:
struct node* create_node(int val) {
// Allocate space for the node, set the fields.
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
temp->data = val;
temp->left = NULL;
temp->right = NULL;
return temp; // Return a pointer to the created node.
}
私の挿入ノード機能:
struct node* insert(struct node *root, struct node *element) {
if (root == NULL)
return element;
else {
// element should be inserted to the right.
if (element->data > root->data) {
// There is a right subtree to insert the node.
if (root->right != NULL)
root->right = insert(root->right, element);
// Place the node directly to the right of root.
else
root->right = element;
}
// element should be inserted to the left.
else {
// There is a left subtree to insert the node.
if (root->left != NULL)
root->left = insert(root->left, element);
// Place the node directly to the left of root.
else
root->left = element;
}
// Return the root pointer of the updated tree.
return root;
}
}
ノードをツリーに挿入している私のメイン:
scanf("%d", &numCases);
for(i=0; i<numCases;i++){
scanf("%d", &numNodes);
for(j=0; j < numNodes; j++){
scanf("%d", &val);
temp_node = create_node(val);
my_root = insert(my_root, temp_node);
}
// calling the function to free the tree after all nodes have been inserted
postOrderFree(my_root);
今、私の計画では、ポスト オーダー トラバース メソッドを使用して各ノードを解放することでしたが、ポスト オーダー機能を使用しようとすると、正しく動作しないようです。ノードはまったく解放されず、私が与えたすべてのケースで、必然的にクラッシュするまで、前のツリーにノードを追加し続けます。
これは、私が使用しようとしている Post order traverse 関数です。
void postOrderFree(struct node* root){
if(root != NULL) {
postOrderFree(root->left);
postOrderFree(root->right);
free(root->data);
}
}
スタイルを含め、冗長性がある場合は、あらゆる助けをいただければ幸いです。