下面是在C中删除一棵树(由GeeksforGeeks提供)#include
#include
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* This function traverses tree in post order to
to delete each and every node of the tree */
void deleteTree(struct node* node)
{
if (node == NULL) return;
/* first delete both subtrees */
deleteTree(node->left);
deleteTree(node->right);
/* then delete the node */
printf("\n Deleting node: %d", node->data);
free(node);
}
/* Driver program to test deleteTree function*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
deleteTree(root);
root = NULL;
printf("\n Tree deleted ");
getchar();
return 0;
}
The above deleteTree() function deletes the tree, but doesn’t change root to NULL which may cause problems if the user of deleteTree() doesn’t change root to NULL and tires to access values using root pointer. We can modify the deleteTree() function to take reference to the root node so that this problem doesn’t occur. See the following code.
#include
#include
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
在C中删除节点可以通过free(node)完成。在Python中,没有这样的方法。在Python中删除节点时,是否需要引用节点的父节点,而在C中则不需要引用?在
(例如,有没有一种方法可以在Python中使用delete(node)而不是{}?在
澄清:
我将在Python中删除如下树(可能有一些错误)。在
^{pr2}$
在提供的C代码中,可以通过释放为特定节点分配的内存来删除节点。但是,在Python中,我需要引用节点的父节点来删除节点。有没有比我的代码更简单的方法从树中删除特定的节点?在