题目描述
给定一颗二叉树的逻辑结构(先序遍历的结果,空树用字符‘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
#include<iostream>
#include<string>
using namespace std;
class BiTreeNode {
public:
int weight;
BiTreeNode* LeftChild;
BiTreeNode* RightChild;
BiTreeNode() :LeftChild(NULL), RightChild(NULL), weight(0) {}
~BiTreeNode() {}
};
class BiTree {
private:
int pos, node_num, max_weight, sum, pos_wt;
string strTree;
int* node_weight;
BiTreeNode* CreateBiTree();
public:
BiTreeNode* Root;
BiTree();
~BiTree() {};
void CreateTree();
void PreOrder(BiTreeNode* p);
void getMax();
};
BiTree::BiTree() {
max_weight = sum = pos_wt = 0;
cin >> strTree;
cin >> node_num;
node_weight = new int[node_num];
for (int i = 0; i < node_num; i++) {
cin >> node_weight[i];
}
}
void BiTree::CreateTree() {
pos = 0;
Root = CreateBiTree();
}
BiTreeNode* BiTree::CreateBiTree() {
BiTreeNode* T;
char ch;
ch = strTree[pos++];
if (ch == '0') {
T = NULL;
}
else {
T = new BiTreeNode();
T->weight = node_weight[pos_wt++];
T->LeftChild = CreateBiTree();
T->RightChild = CreateBiTree();
}
return T;
}
void BiTree::PreOrder(BiTreeNode* p) {
if (p) {
if (p->LeftChild && p->RightChild) {
p->LeftChild->weight += p->weight;
p->RightChild->weight += p->weight;
}
else if (p->LeftChild)
p->LeftChild->weight += p->weight;
else if (p->RightChild)
p->RightChild->weight += p->weight;
max_weight = max_weight > p->weight ? max_weight : p->weight;
PreOrder(p->LeftChild);
PreOrder(p->RightChild);
}
}
void BiTree::getMax() {
PreOrder(Root);
cout << max_weight << endl;
}
int main() {
int t;
cin >> t;
while (t--) {
BiTree bt;
bt.CreateTree();
bt.getMax();
}
return 0;
}