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

题目描述

给定一颗二叉树的逻辑结构(先序遍历的结果,空树用字符‘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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值