c++ iteratively destroying a binary tree -
i trying write code iteratively destroys binary tree. know recursion easier, thought try iteratively (albeit using c notation , using structures, no need classes). thinking 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 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 value: " << p_tree->key_value << endl; delete p_tree; p_tree = null;
}
i don't know wrong logic. goes this. traverse down binary tree until hit node no children, delete node. repeat until have original parent node. delete that.
edit: i've changed code in response suggestions. seems work , there no infinite loop, when try print out contents of binary tree, function gets stuck in infinite loop. know print function correct, there must still wrong delete_tree function.
one error here:
while (local_node->p_left != null && local_node->p_left != null)
you're iterating downwards while node has 2 children. want check ||
instead of &&
.
Comments
Post a Comment