以下是在C语言中删除一棵树的代码(由GeeksforGeeks提供):
在C语言中,可以通过
(即,在Python中是否有一种方法可以执行
#include<stdio.h>
#include<stdlib.h>
/* 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<stdio.h>
#include<stdlib.h>
/* 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)
而不是parent.left = None
?)
澄清:
我想在Python中删除如下所示的树(可能存在一些错误)。def delete_tree(root, parent):
if not root:
return
if not root.left and not root.right:
if root is parent.left:
parent.left = None
else:
parent.right = None
delete_tree(root.left, root)
delete_tree(root.right, root)
root = None
在提供的C代码中,可以通过释放特定节点分配的内存来删除节点。然而,在Python中,我需要一个指向节点父级的引用来删除节点。有没有比我的代码更简单的方法从树中删除特定的节点?
__del__
并且可能存在循环引用? - Hyperboreusmalloc()
也没有free()
。忘记它们的存在,你会更开心;-)“如何在Python中删除一棵树?”你不需要这样做。当你的程序停止引用它时,它会自动消失。如果你愿意,你可以浪费时间将东西设置为None
,但这并不是必要的。 - Tim Peters__del__
方法可能会创建永久循环垃圾。但在下一个Python 3版本中,它们将不再这样了 :-) - Tim Peters