无效递归从BST删除节点和所有子节点 [英] Void Recursion To Delete Node And All Child Nodes From BST

查看:106
本文介绍了无效递归从BST删除节点和所有子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个void删除搜索并检查树是否包含具有传递值的节点,然后将找到的节点传递给第二个删除void。

第二个删除void应该能够递归删除传递的节点和所有它的子节点aka,childen。



如果使用第二个void删除方法我试图在循环中删除找到的节点,我得到NullReferenceExeption。



我发现了无数的视频和教程使用bool,节点和其他删除方法,但没有任何虚空,所以任何帮助将不胜感激!



The first void Remove searches and checks whether the tree contains a node with the passed value, then passes the found node to second Remove void.
Second remove void should be able to recursively remove the passed node and all it's sub nodes aka, childen.

If using the second void Remove method I attempt to remove the found nodes while cycling through them, I get NullReferenceExeption.

I've found countless of videos and tutorials using bool, node and other Remove methods, but none with void, so any help would be appreciated!

public void Remove(int number)
{
    BNode currentnode = Root;

    if (currentnode == null)
    {
        Console.WriteLine("Tree is empty!");
    }

    if (currentnode.Number != number)
    {
        currentnode = FindNode(number, currentnode);
    }

    Remove(currentnode);
}




public void Remove(BNode node)
{

    if (node == null)
    {
        return;
    }

    Remove(node.LeftNode);

    node = null;

    Remove(node.RightNode);

    // fails to execute
}



提前谢谢!


Thank you in advance!

推荐答案

删除方法:



  1. 您不检查给定的节点 null
  2. 执行实际删除节点的代码在哪里?

好像它应该是这样的:

public void Remove(BNode node)
{
    if (node == null)
    {
        return;
    }

    Remove(node.LeftNode);
    Remove(node.RightNode);

    // Remove the current node (the parameter).
}


这篇关于无效递归从BST删除节点和所有子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆