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 方法来释放每个节点,但是当我尝试使用我的 Post order 功能时,它似乎无法正常工作。它根本不会释放任何节点,并且对于我给它的每种情况,它都会继续向前一个树添加节点,直到它不可避免地崩溃。
这是我正在尝试使用的 Post order traverse 函数:
void postOrderFree(struct node* root){
if(root != NULL) {
postOrderFree(root->left);
postOrderFree(root->right);
free(root->data);
}
}
任何和所有的帮助将不胜感激,包括风格和是否有任何冗余!