DS树--二叉树之最大路径

时间限制1s

内存限制128MB

题目描述

给定一颗二叉树的逻辑结构(先序遍历的结果,空树用字符‘0’表示,例如AB0C00D00),建立该二叉树的二叉链式存储结构

二叉树的每个结点都有一个权值,从根结点到每个叶子结点将形成一条路径,每条路径的权值等于路径上所有结点的权值和。编程求出二叉树的最大路径权值。如下图所示,共有4个叶子即有4条路径,

路径1权值=5 + 4 + 11 + 7 = 27路径2权值=5 + 4 + 11 + 2 = 22

路径3权值=5 + 8 + 13 = 26路径4权值=5 + 8 + 4 + 1 = 18

可计算出最大路径权值是27。

该树输入的先序遍历结果为ABCD00E000FG00H0I00,各结点权值为:

A-5,B-4,C-11,D-7,E-2,F-8,G-13,H-4,I-1

输入

第一行输入一个整数t,表示有t个测试数据

第二行输入一棵二叉树的先序遍历,每个结点用字母表示

第三行先输入n表示二叉树的结点数量,然后输入每个结点的权值,权值顺序与前面结点输入顺序对应

以此类推输入下一棵二叉树

输出

每行输出每棵二叉树的最大路径权值,如果最大路径权值有重复,只输出1个

#include <iostream>
#include <string>
using namespace std;
class BiTreeNode {
public:
	char  data;	//数据域
    int weight;

	BiTreeNode  *leftChild,  *rightChild,*parent;	//左右子树指针
	BiTreeNode():leftChild(NULL), rightChild(NULL),parent(NULL){}
	~BiTreeNode() {}
};

class BiTree {
private:

	BiTreeNode *root;	//根结点指针
	string sTree;		//建树字符串
	int pos,pos2;			//标识建树字符串的当前字符位置
	BiTreeNode * CreateTree(int w1[]);//建树私有函数
public:
    int max=0;
	BiTree():root(NULL) {};
	void Create(string vArray,int w1[]);	//建树公有接口,参数是特定的先序遍历字符串
	int findparent(BiTreeNode* T,int sum){
        if(T!=root){
            sum+=T->weight;
            sum= findparent(T->parent,sum);
        }
        return sum;
    }
    void findchild(){
        findchild(root);
    }
    void findchild(BiTreeNode* T){
        if(T){
            if(!T->leftChild&&!T->rightChild){
                int sum=findparent(T,0);
                sum+=root->weight;
                if(max<sum) max=sum;
            }
            findchild(T->leftChild);
            findchild(T->rightChild);
        }
    }

};
void BiTree::Create(string vArray,int w1[])
{	pos=0;pos2=0;
	sTree.assign(vArray);	//把参数保存到内部字符串
	root = CreateTree(w1);	//建树成功后root指向根结点
}
//请完成上述类内部的私有函数实现
BiTreeNode* BiTree::CreateTree(int w1[]){
    BiTreeNode* T;
    char ch= sTree[pos++] ;
    if(ch=='0') T=NULL;
    else {
        T=new BiTreeNode;
        T->data=ch;
        T->weight=w1[pos2++];

        T->leftChild=CreateTree(w1);
        if(T->leftChild) T->leftChild->parent=T;
        T->rightChild=CreateTree(w1);
        if(T->rightChild) T->rightChild->parent=T;
    }
    return T;
}
//主函数
int main()
{	int t;
	string vArray;
	cin>>t;
	while(t--)
	{	cin>>vArray;
        int n;cin>>n;int w[n];
        for (int i = 0; i < n; ++i) {
            cin>>w[i];
        }
		BiTree myTree;
		myTree.Create(vArray,w);
        myTree.findchild();
        cout<<myTree.max<<endl;
	}
	return 0;
}


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值