【发布时间】:2013-11-18 06:05:12
【问题描述】:
以下是在C中删除一棵树(GeeksforGeeks提供)
#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);
}
可以通过free(node) 删除 C 中的节点。在 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 中,我需要引用节点的父节点来删除节点。有没有比我的代码更简单的方法从树中删除特定节点?
【问题讨论】:
-
不清楚你想要完成什么:Python 使用垃圾收集 - 永远不需要显式释放对象。如果你用完了一棵树,它的内存将在对树的最后一次引用消失后自动回收。
-
@TimPeters 这是真的吗?甚至实现
__del__并且可能有循环引用? -
谢谢@TimPeters。你能看看更新吗?我的问题的一个更一般的版本实际上是“你如何在 Python 中删除一棵树?”但我想解决 C 从树中删除节点的方式与 Python 的方式之间的区别。
-
@MaximusS,对不起,我仍然不明白你想要完成什么。 Python 既没有
malloc()也没有free()。忘记它们的存在,你会更快乐 ;-) “你如何在 Python 中删除一棵树?”你没有。当您的程序停止引用它时,它会自行消失。您可以浪费时间;-) 如果您愿意,可以将内容设置为None,但这不是必需的。 -
@Hyperboreus,是的
__del__方法可以创建不朽的循环垃圾。但在下一个 Python 3 版本中它们将不再存在 :-)
标签: python tree binary-search-tree