参考资料:《数据结构与算法分析——C语言描述》4.3一节
#include<stdio.h> #include<stdlib.h> #define N 10 typedef struct BinTreeNode { int data; struct BinTreeNode *left; struct BinTreeNode *right; }BinTreeNode,*BinTree; BinTree insert(BinTree T,int data);//二叉树节点的添加 void PrintTree(BinTree T,void (*p)(BinTree T));//打印操作 void PrintTreeNode(BinTree T);//打印一个节点 BinTree Delete(BinTree T,int data);//删除某个节点 BinTree FindMin(BinTree T);//查找最小节点 BinTree FindMax(BinTree T);//查找最大节点 int FindMaxSubMin(BinTree T);//最大节点与最小节点的差值 int main() { int i=0,n=0; int data[N]= {10,23,11,98,111,87,34,11,154,4}; BinTreeNode *root=NULL; BinTree p; for(i=0;i<N;i++) { root=insert(root,data[i]); } PrintTree(root,PrintTreeNode); n=FindMaxSubMin(root); printf("%d\n",n); p=FindMin(root); PrintTreeNode(p); p=FindMax(root); PrintTreeNode(p); printf("\n"); root=Delete(root,154); printf("\n"); PrintTree(root,PrintTreeNode); printf("\n"); n=FindMaxSubMin(root); printf("%d\n",n); p=FindMin(root); PrintTreeNode(p); p=FindMax(root); PrintTreeNode(p); root=Delete(root,1154); free(root); free(p); return 0; } BinTree insert(BinTree T,int data) { if(T==NULL) { T=malloc(sizeof(BinTreeNode)); if(T==NULL) printf("Out of space!\n"); else { T->data=data; T->left=NULL; T->right=NULL; } } else { if(data<T->data) T->left=insert(T->left,data); else T->right=insert(T->right,data); } return T; } void PrintTreeNode(BinTree T) { printf("%d\t",T->data); } //中序遍历 void PrintTree(BinTree T,void (*p)(BinTree T)) { if(T!=NULL) { PrintTree(T->left,p);//打印左子树 p(T);//打印节点 PrintTree(T->right,p);//打印右子树 } } BinTree Delete(BinTree T,int data) { BinTree temp; if(T==NULL) printf("\n%d not found.\n",data); else { if(data<T->data) T->left=Delete(T->left,data); else { if(data>T->data) T->right=Delete(T->right,data); else { if( T->left && T->right)//two children { temp=FindMin(T->right); T->data=temp->data; T->right=Delete(T->right,T->data); } else//one or zero child { temp=T; if(T->left==NULL) T=T->right; else { if(T->right==NULL) T=T->left; } free(temp); } } } } return T; } BinTree FindMin(BinTree T) { if(T==NULL) return NULL; else if(T->left==NULL) return T; else return FindMin(T->left); } BinTree FindMax(BinTree T) { if(T==NULL) return NULL; else if(T->right==NULL) return T; else return FindMax(T->right); } int FindMaxSubMin(BinTree T) { int Max,Min; BinTree p; p=T; if(T==NULL) return 0; while(T->left!=NULL) T=T->left; Min=T->data; while(p->right) p=p->right; Max=p->data; return (Max-Min); }
原文地址:http://blog.csdn.net/u010275850/article/details/44925853