You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <vector>
#include <string>
#include <stdlib.h>
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<int> maxpath; //全局变量:存放最大路径
void Findmaxpath(BTNode* bt, vector <int > apath, int asum)
//求根结点到叶结点的路径和最大的路径
{
if (bt == NULL) //空树直接返回
return;
apath.push_back(bt->data);
asum += bt->data; //bt结点加入apath
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<int> 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);
}