算法入门经典第六章 例题6-8 树
生活随笔
收集整理的這篇文章主要介紹了
算法入门经典第六章 例题6-8 树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
題意:
給一棵點帶權的二叉樹的中序和后序遍歷,找一個葉子使得它到根的路徑上的權值的和最小,如果多解,那該葉子本身的權值應該最小
?
?
解題思路:
1.用getline()輸入整行字符,然后用stringstream獲得字符串中的數字? 2.用數組in_oder[]和post_order[]分別表示中序遍歷和后序遍歷的順序,用數組rch[]和lch[]分別表示結點的左子樹和右子樹
3.用遞歸的辦法根據遍歷的結果還原二叉樹(后序遍歷的最后一個樹表示的是根節點,中序遍歷的中間一個表示根節點
4.二叉樹構造完成后,再執行一次遞歸遍歷找出最優解
?
#include<iostream> #include<string> #include<sstream> #include<algorithm> using namespace std; // 因為各個結點的權值各不相同且都是正整數,直接用權值作為結點編號 用數組存儲二叉樹 const int maxv = 10000 + 10; int in_order[maxv], post_order[maxv], lch[maxv], rch[maxv]; int n; bool read_list(int *a){ string line; if(!getline(cin,line))return false; stringstream ss(line); n=0; int x; while(ss>>x) a[n++]=x; return n>0;}// 把in_order[L1..R1] 和 post_order[L2..R2]建成一棵二叉樹, 返回樹根 int build(int L1,int R1,int L2,int R2) {//最后的葉沒有左右子樹 如果有一個葉是5 則lch[5]=0 rch[5]=0 if(L1>R1) return 0;//空樹 遞歸邊界 int root=post_order[R2];// int p=L1;//找到根節點在中序排列中的位置 while(in_order[p]!=root) p++; int cnt=p-L1;//左子樹的節點個數 lch[root]=build(L1,p-1,L2,L2+cnt-1); rch[root]=build(p+1,R1,L2+cnt,R2-1); return root;//遞歸法 lch[2]=5,權值為2的左結點為5 }int best,best_sum;//目前為止的最優解和對應的權和 void dfs(int u, int sum) {sum += u;if(!lch[u] && !rch[u]) { // 葉子if(sum < best_sum || (sum == best_sum && u < best)) { best = u; best_sum = sum; }}if(lch[u]) dfs(lch[u], sum);if(rch[u]) dfs(rch[u], sum); }int main() {while(read_list(in_order)) {read_list(post_order);build(0, n-1, 0, n-1);best_sum = 1000000000;dfs(post_order[n-1], 0);cout << best << "\n";}return 0; }?
轉載于:https://www.cnblogs.com/is-Tina/p/7422485.html
總結
以上是生活随笔為你收集整理的算法入门经典第六章 例题6-8 树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: V-rep学习笔记:机器人逆运动学解算
- 下一篇: ansible 安装和使用