我有一个二进制搜索树,当我尝试使用单个孩子删除节点的情况时,您会删除节点并将子节点移至其位置。我有代码,但每当我这样做时,它都会给我一个糟糕的指针。
这是代码的段
else if((root->Left != NULL) != (root->Right != NULL)){ //Checks if it's a on child node
if(root->Left != NULL){ //If it has a left child, attempts to move the left child to existing node
delete root;
root = root->Left;
}
else{ //If it is right child, attempts to move right child to existing node
delete root;
root = root->Right;
}
}
结构有值
DATA_TYPE Value;
TreeNode* Left;
TreeNode* Right;
我知道我是从调试器分配错误的,那么移动节点的正确方法是什么?
编辑:
不知道我是如何错过的,但是删除它后正在使用root
。
edit2:您需要一个临时。
TreeNode* temp = root->Right;
delete root;
root = temp;
这是方法
的Java实现public void removeHalfNodes () {
if ( root == null ) return;
if ( root.left == null && root.right == null ) return;
if ( root.left == null && root.right != null ) root = root.right;
else if ( root.left != null && root.right == null )
root = root.left;
removeHalfNodesRec ( root );
}
public void removeHalfNodesRec ( BinaryTreeNode node ) {
if ( node.left != null ) {
if ( node.left.left == null && node.left.right != null )
node.left = node.left.right;
else if ( node.left.right == null && node.left.left != null )
node.left = node.left.left;
removeHalfNodesRec ( node.left );
}
if ( node.right != null ) {
if ( node.right.left == null && node.right.right != null )
node.right = node.right.right;
else if ( node.right.right == null && node.right.left != null )
node.right = node.right.left;
removeHalfNodesRec ( node.right );
}
}