当前位置: 首页 > 后端技术 > PHP

4.4数据结构(PHP实现)——二叉搜索树的节点删除

时间:2023-03-30 01:44:40 PHP

1.删??除逻辑删除节点的左孩子:被删除节点没有右孩子:被删除节点有左孩子和右孩子:被删除节点左边的所有值都会小于节点,所以只要取最大值替换为这个节点2.代码rootNode;$parentNode=null;while(!is_null($node)){if(bccomp($node->getValue(),$value)>0){$parentNode=$node;$node=$node->getLeftChild();}elseif(bccomp($node->getValue(),$value)<0){$parentNode=$node;$node=$node->getRightChild();}else{//如果没有右孩子,那么左孩子可以直接链接到父节点if(is_null($node->getRightChild())){//将新节点连接到父节点,这里判断是父节点的左孩子还是右孩子if(!is_null($parentNode->getLeftChild())&&bccomp($parentNode->getLeftChild()->getValue(),$node->getValue())==0){$parentNode->setLeftChild($node->getLeftChild());}elseif(!is_null($parentNode->getRightChild())&&bccomp($parentNode->getRightChild()->getValue(),$node->getValue())==0){$parentNode->setRightChild($节点->getLeftChild());}返回;}//如果没有左孩子,右孩子可以直接连接到父节点if(is_null($node->getLeftChild())){//将新节点连接到父节点,这里是必须的判断是父节点的左孩子还是右孩子if(!is_null($parentNode->getLeftChild())&&bccomp($parentNode->getLeftChild()->getValue(),$node->getValue())==0){$parentNode->setLeftChild($node->getRightChild());}否则(!我s_null($parentNode->getRightChild())&&bccomp($parentNode->getRightChild()->getValue(),$node->getValue())==0){$parentNode->setRightChild($node->getRightChild());}返回;}//如果左右儿子都存在,则取右儿子中的最小节点替换本节点//定义当前节点左儿子最大节点的父节点$leftMaxNodeParent=$node;//定义当前节点左孩子的最大节点$leftMaxNode=$leftMaxNodeParent->getLeftChild();//遍历while(!is_null($leftMaxNode)&&!is_null($leftMaxNode->getRightChild())){$leftMaxNodeParent=$leftMaxNode;$leftMaxNode=$leftMaxNode->getRightChild();}//将当前节点的左孩子的最大节点的父节点的右孩子设置为null$leftMaxNodeParent->setRightChild(null);//将当前节点的左儿子的最大节点的左儿子和右儿子设置为该节点的左儿子和右儿子$leftMaxNode->setLeftChild($node->getLeftChild());$leftMaxNode->setRightChild($node->getRightChild());//将新节点连接到父节点,这里需要判断是父节点的左孩子还是右孩子if(!is_null($parentNode->getLeftChild())&&bccomp($parentNode->getLeftChild()->getValue(),$node->getValue())==0){$parentNode->setLeftChild($leftMaxNode);}elseif(!is_null($parentNode->getRightChild())&&bccomp($parentNode->getRightChild()->getValue(),$node->getValue())==0){$parentNode->setRightChild($左最大节点);}返回;}}}//...其他代码}