1. 程式人生 > >DS樹+圖綜合練習--二叉樹之最大路徑

DS樹+圖綜合練習--二叉樹之最大路徑

ostream tree ring 一行 {} 等於 content man mil

題目描述

給定一顆二叉樹的邏輯結構(先序遍歷的結果,空樹用字符‘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-5B-4C-11D-7E-2F-8G-13H-4I-1

技術分享圖片

輸入

第一行輸入一個整數t,表示有t個測試數據

第二行輸入一棵二叉樹的先序遍歷,每個結點用字母表示

第三行先輸入n表示二叉樹的結點數量,然後輸入每個結點的權值,權值順序與前面結點輸入順序對應

以此類推輸入下一棵二叉樹

輸出

每行輸出每棵二叉樹的最大路徑權值,如果最大路徑權值有重復,只輸出1個

樣例輸入

2 AB0C00D00 4 5 3 2 6 ABCD00E000FG00H0I00 9 5 4 11 7 2 8 13 4 1

樣例輸出

11

27

這裏只需給每個樹節點添加屬性weight即可,在創建樹的時候每次傳入父節點的weight,孩子節點叠代相加即可,並在類中設置屬性maxleaveweight來記錄葉子節點的最大權值,在創建樹的時候就可以判斷了,不需要再次調用任何一種遍歷來設置maxleaveweigth

#include<iostream>
#include<string>
using namespace std;
class BitreeNode
{
public:
    char data;
    int weight;
    int hight;
    BitreeNode *left;
    BitreeNode *right;
    BitreeNode() :hight(0),weight(0),left(NULL), right(NULL) {}
    ~BitreeNode() {}
};
class Bitree
{
private:
    BitreeNode 
*Root; int pos,po; string strtree; BitreeNode *CreateBitree(int w[],int fatherweight); void preorder(BitreeNode *t); public: int maxleaveweight; Bitree() { maxleaveweight = 0; }; ~Bitree() {}; void CreateTree(string TreeArray,int w[]); void preorder(); }; void Bitree::CreateTree(string treearray,int w[]) { pos = 0; po = 0; strtree.assign(treearray); Root = CreateBitree(w,0); } BitreeNode *Bitree::CreateBitree(int w[],int fatherweight) { BitreeNode *T; char ch; ch = strtree[pos++]; if (ch == 0) T = NULL; else { T = new BitreeNode(); T->data = ch; T->weight = w[po++]+fatherweight; if (!T->left && !T->right) if (T->weight > maxleaveweight) maxleaveweight = T->weight; T->left = CreateBitree(w,T->weight); T->right = CreateBitree(w,T->weight); } return T; } void Bitree::preorder() { preorder(Root); cout << maxleaveweight << endl; } void Bitree::preorder(BitreeNode *t) { if (t) { if (!t->left && !t->right) if (t->weight > maxleaveweight) maxleaveweight = t->weight; preorder(t->left); preorder(t->right); } } int main() { int t; cin >> t; while (t--) { string str; cin >> str; Bitree *tree; int n,*w; cin >> n; w = new int[n]; for (int i = 0; i < n; i++) cin >> w[i]; tree = new Bitree(); tree->CreateTree(str,w); cout << tree->maxleaveweight << endl; } }

DS樹+圖綜合練習--二叉樹之最大路徑