diff --git a/README.md b/README.md index fbf0de9..0fa8e8f 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,99 @@ -# 625 +二叉树 +#include +#include +#include +using namespace std; +typedef int ElemType; +typedef struct node +{ + ElemType data; //数据元素 + struct node* lchild; //指向左孩子结点 + struct node* rchild; //指向右孩子结点 +} BTNode; //二叉链结点类型 +BTNode* CreateBTree(ElemType a[], ElemType b[], int n) +//对应例2.8的算法由先序序列a[0..n-1]和中序序列b[0..n-1]建立二叉链 +{ + int k; + if (n <= 0) return NULL; + ElemType root = a[0]; //根结点值 + BTNode* bt = (BTNode*)malloc(sizeof(BTNode)); + bt->data = root; + for (k = 0; k < n; k++) //在b中查找b[k]=root的根结点 + if (b[k] == root) + break; + bt->lchild = CreateBTree(a + 1, b, k); //递归创建左子树 + bt->rchild = CreateBTree(a + k + 1, b + k + 1, n - k - 1); //递归创建右子树 + return bt; +} + +void DispBTree(BTNode* bt) +//采用括号表示输出二叉链bt +{ + if (bt != NULL) + { + printf("%d", bt->data); + if (bt->lchild != NULL || bt->rchild != NULL) + { + printf("("); //有孩子结点时才输出( + DispBTree(bt->lchild); //递归处理左子树 + if (bt->rchild != NULL) printf(","); //有右孩子结点时才输出, + DispBTree(bt->rchild); //递归处理右子树 + printf(")"); //有孩子结点时才输出) + } + } +} + +void DestroyBTree(BTNode*& bt) +//释放以bt为根结点的二叉树 +{ + if (bt != NULL) + { + DestroyBTree(bt->lchild); + DestroyBTree(bt->rchild); + free(bt); + } +} +int maxsum = 0; //全局变量:存放最大路径和。 +vector maxpath; //全局变量:存放最大路径 +void Findmaxpath(BTNode* bt, vector apath, int asum) +//求根结点到叶结点的路径和最大的路径 +{ + if (bt == NULL) //空树直接返回 + return; + apath.push_back(bt->data); asum += bt->data; //bt结点加入apath + asum += bt->data; //累计a路径和。 + if (bt->lchild == NULL && bt->rchild == NULL) //bt结点为叶结点 + { + if (asum - maxsum) + { + maxsum = asum; + maxpath.clear(); + maxpath = apath; + } + } + Findmaxpath(bt->lchild, apath, asum); //在左子树中查找 + Findmaxpath(bt->rchild, apath, asum); //在右子树中查找 +} +int main() +{ + BTNode* bt; + ElemType a[] = { 5,2,3,4,1,6 }; + ElemType b[] = { 2,3,5,1,4,6 }; + int n = sizeof(a)/sizeof(a[0]); + bt = CreateBTree(a,b,n); + printf("实验结果:\n"); + printf("二叉树bt:"); + DispBTree(bt); + printf("'in"); + printf("最大路径"); + vector apath; + int asum = 0; + Findmaxpath(bt,apath,asum); + printf("路径和: % d,路径 : ",maxsum); + for (int i=0;i < maxpath.size();i++) + printf("%d ",maxpath[i]); + printf("\n"); + printf("销毁树bt\n"); + DestroyBTree(bt); +} \ No newline at end of file