【资料结构】二元树的删除

说明

说明

1.根结点中的两边固定一边大另一边小。2.下方节点当作新的根结点,继续符合一边大一边小的规则。3.无重複值。4.二元搜寻树是进行搜寻、插入、删除最好的资料结构。

程式

前置準备

#include <stdbool.h>#include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct tree *tree_p;struct tree {  int data;  tree_p left;  tree_p right;  bool t_left;  bool t_right;  tree_p back;} tree;

副函式

tree_p max_p(tree_p root):找寻该根最大节点

带入树的某节点,利用搜寻树最大值放右侧的特性,可回传该根最大位址
tree_p max_p(tree_p root) {  tree_p temp = NULL;  while (root != NULL) {    temp = root;    root = root->right;  }  return temp;}

tree_p del(tree_p point, int num):删除节点

带入某树根与欲删除点,可经过三种不同情况的判断将结点删除
tree_p del(tree_p point, int num) {  tree_p temp = point;  if (point == NULL) {    printf("%d does not exist in the tree.\n",num);    //节点不存在  } else if (point->data > num) {    point->left = del(point->left, num);  } else if (point->data < num) {    point->right = del(point->right, num);  }//节点以搜寻树的方式,利用递迴找址   else {    //找到位址      if (point->left != NULL && point->right != NULL) {       //有左右节点,找寻该根最大值取代欲删除点,并将最大值位置删除      temp = max_p(point->left);      point->data = temp->data;      point->left = del(point->left, temp->data);    } else {        //只有一个左右节点或无左右节点      if (point->left == NULL) {        point = point->right;      } else if (point->right == NULL) {        point = point->left;      }    }  }  return point;}

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章