树2——删除节点与求度,高度

来源:互联网 发布:德州扑克 mac 编辑:程序博客网 时间:2024/06/14 06:52

接着上一次的内容,本文继续介绍一些关于树的操作。

删除节点:

    TreeNode* current = tree->head->next;      for (i = 0; i < pos; i++)    {        current = current->next;    }    *x = current->data;    r_delete(tree, current);

删除一个节点,我们必须删除这个节点以及他的“子子孙孙”,这样用一般的方法就很难操作,于是我们可以引入递归的思想,从他的“子子孙孙”开始删除,一直删到他自己。这样就比较简单了。当然之前我们必须遍历树将他找到,在进行递归删除。
下面是递归删除函数内容:

// 从树链表中移除这个结点,找node的前一个结点    TreeNode* tmp = tree->head; // 链表的头节点    while (tmp->next)    {        if (tmp->next == node)        {            tmp->next = node->next;            tree->len --;            break;        }        tmp = tmp->next;    }    // 将父亲结点中子结点链表中指向node的结点删除    TreeNode* parent = node->parent;    if (parent != NULL)    {        ChildNode* tmp = parent->childList;  // 子结点链表的头节点        while (tmp->next)        {            if (tmp->next->childNode == node)            {                ChildNode* p = tmp->next;                tmp->next = p->next;                free(p);                parent->degree--;                break;            }            tmp = tmp->next;        }    }    // 将该结点的孩子结点删掉    ChildNode* child = node->childList->next;   // 子结点链表中的第一个结点    while (child)    {        ChildNode* pchild = child->next;        r_delete(tree, child->childNode);        child  = pchild;    }    free (node->childList);    free (node);

其基本的思想就是删自己和自己的孩子,然后孩子又删自己和自己的孩子,如此下去。。。整个过程与插入一样都是比较复杂的。

求树高度:

int r_height(TreeNode* node){    if (node == NULL)        return 0;    int subHeight = 0;    int max = 0;    ChildNode* child = node->childList->next;    while (child)    {        subHeight = r_height(child->childNode);        if (subHeight > max)            max = subHeight;        child = child->next;    }    return max + 1;}

求树的高度,换句话说不就是求他子树中最高那棵的高度再加上一吗?这样又用到了递归的思想,递归函数如上。这样就相对简单许多了,也比较好理解了。

求树的度:

int r_degree(TreeNode* node){    if (node == NULL)        return 0;    int max = node->degree;    int subDegree = 0;    ChildNode* child = node->childList->next;    while (child)    {        subDegree = r_degree(child->childNode);        if (subDegree > max)            max = subDegree;        child = child->next;    }    return max;}

获取树的度与获取高度很相似,同样也用到了递归的思想,由此可见递归的思想还是很重要的,在这三个操作中都用到了递归的思想。

关于树的操作远远不止这些但其他的一些相对这几个操作就简单许多了,所以就不多讲了。

阅读全文
0 0
原创粉丝点击