c++ - 从二叉树中删除并查找节点

标签 c++ binary-tree treenode

我正在为普通二叉树(不是搜索)创建“查找”和“删除”功能。下面是查找函数的代码:

bool Find_Node(FileItem * item, Node *current )  //function starts with root
{
    if (current->getNameItem() == item->getName() )  //getNameItem() retrieves the data name in node.
    {
        currentItem = current;   //I have set currentItem as an attribute ( pointer to a Node ) in the tree class. I created it to point to the node I want to find.
        return true;
    }
    Node* child [2];

    child[0] = current->getLeft();
    child[1] = current->getRight();

    bool res = false;

    for (int i = 0; res == false && i < 2 ; i++) 
    {   
        if(child[i] != NULL)
            res = Find_Node(item, child[i]);
    }
    return res;
}

有没有更好的方法来查找节点?请有人帮我删除功能。

最佳答案

添加NULL的基本情况以使逻辑简单。

bool Find_Node(FileItem * item, Node *current )
{
    if(current == NULL ) return false;
    if (current->getNameItem() == item->getName() ) {
        currentItem = current;
        return true;
    }
    return Find_Node(current->getLeft()) || Find_Node(current->getRight());
}

void Delete_Node(Node*& current)
{
    if(current == NULL) return;
    Delete_Node(current->getRight());
    Delete_Node(current->getLeft());
    delete current;
    current = NULL;
}

如果我能看到 Node 的实现,我可以告诉您如何实现您需要的 swap 功能

如果树真的很大这可能会导致堆栈溢出。但这个问题可以通过将解决方案从递归解决方案更改为迭代解决方案来解决。

关于c++ - 从二叉树中删除并查找节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13519494/

相关文章:

C++ 新手尝试循环

c++ - 检查哪个套接字首先回答 C++

c++ - 使用Qt模拟gps数据以与traccar一起使用

algorithm - 不相交集数据结构和二叉树?

java - Java 的 AVL 树

java - 打印二叉搜索树中序遍历

c++ - OpenCV 类型独立图像访问的最佳方式?

java - 实现java接口(interface)时保证 "Object o"参数是同一个泛型类型

algorithm - 使用隐式 key 进行 Treap

c++ - C++ 中的 AVL 树再平衡