[英]c++ iteratively destroying a binary tree
I was trying to write a code that iteratively destroys a binary tree. 我试图编写一个迭代破坏二叉树的代码。 I know that recursion is much easier, but I thought I would try to do it iteratively (albeit using mostly C notation and using only structures, no need for classes).
我知道递归更容易,但我想我会尝试迭代地做(虽然主要使用C表示法并且只使用结构,不需要类)。 My thinking was something like the following:
我的想法如下:
void delete_tree (node *p_tree){
node *local_node;
node *parent;
int left_or_right;
while (p_tree->p_left != NULL || p_tree->p_right != NULL){
parent = p_tree;
if (parent->p_left != NULL){
local_node = parent->p_left;
left_or_right = 1;
} else {
local_node = parent->p_right;
left_or_right = 2;
}
while (local_node->p_left != NULL || local_node->p_right != NULL){
if (local_node->p_left == NULL){
parent = local_node;
local_node = local_node->p_right;
left_or_right = 2;
} else if (local_node ->p_right == NULL){
parent = local_node;
local_node = local_node->p_left;
left_or_right = 1;
} else {
parent = local_node;
local_node = local_node->p_left;
left_or_right = 1;
}
}
cout << "Deleting node with value: " << local_node->key_value << endl;
delete local_node;
local_node = NULL;
if (left_or_right == 1){
parent->p_left = NULL;
} else if (left_or_right == 2){
parent->p_right = NULL;
}
}
cout << "Deleting node with value: " << p_tree->key_value << endl;
delete p_tree;
p_tree = NULL;
} }
I don't know what is wrong with my logic. 我不知道我的逻辑有什么问题。 It goes like this.
它是这样的。 Traverse down the binary tree until we hit a node with no children, then delete that node.
遍历二叉树,直到我们命中没有子节点的节点,然后删除该节点。 Repeat until we just have the original parent node.
重复,直到我们只有原始父节点。 Then finally delete that.
然后最后删除。
Edit: I've changed the code in response to the suggestions. 编辑:我已经更改了代码以响应建议。 It now seems to work and there is no infinite loop, but when I try to print out the contents of the binary tree, that function gets stuck in an infinite loop.
它现在似乎工作并且没有无限循环,但是当我尝试打印出二叉树的内容时,该函数会陷入无限循环。 I know my print function is correct, so there must still be something wrong with this delete_tree function.
我知道我的打印功能是正确的,所以这个delete_tree函数仍然有问题。
One error is here: 一个错误在这里:
while (local_node->p_left != NULL && local_node->p_left != NULL)
You're only iterating downwards while the node has two children. 当节点有两个孩子时,你只是向下迭代。 You want to check
||
你想检查一下
||
instead of &&
. 而不是
&&
。
I would do it with a stack of pointers to nodes. 我会用一堆指向节点的指针来做。 Some like this:
有人喜欢这样:
void preOrderStack_aux(node *p)
{
if (p == NULL)
return;
stack_t stack;
stack_push(p);
while (not stack_is_empty(stack))
{
p = stack_pop(stack);
if (p->p_right != NULL)
stack_push(p->p_right);
if (LLINK(p) != NULL)
stack_push(p->p_link);
// here stack has stored descendents
free(p);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.