二叉樹3(恢復二叉樹)
阿新 • • 發佈:2018-05-12
恢復 code std spa element this \n turn cout
從中序和後序恢復二叉樹
給一顆帶權(權值各不相同,都是小於10000的正整數)的二叉樹的中序和後序遍歷序列,找一個葉子使得它到根的路徑上的權值盡可能小,如果有多解,取葉子權值小的。輸入中第一行為中序遍歷,第二行為後序遍歷。
例如輸入:
3 2 1 4 5 7 6
3 1 2 5 6 7 4
輸出
1
輸入:
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
輸出:
3
#include"iostream" using namespace std; typedef int element; element minweight = 20000; element minleaf; classTree{ private: element data; Tree *right,*left; public: Tree(element data = 0){ this->data = data; right = NULL; left = NULL; } void usezhCreate(Tree* &t,element *z,element *h,int len){ if(len == 1){ t = new Tree(z[0]); //如果還剩1個值了,直接創建葉子} else{ int llen = 0; //左子樹長度 for(int i = 0;i < len;i++){ if(z[i] == h[len - 1]){ llen = i; break; } } int rlen = len - llen - 1; //右子樹長度 element *zl = newelement[llen]; element *zr = new element[rlen]; element *hl = new element[llen]; element *hr = new element[rlen]; //核心拆分 for(i = 0;i < llen;i++){ zl[i] = z[i]; hl[i] = h[i]; } for(i = 0;i < rlen;i++){ zr[i] = z[i + llen + 1]; hr[i] = h[i + llen]; } t = new Tree(h[len - 1]); //長度大於0 就繼續創建樹 if(llen > 0){ usezhCreate(t->left,zl,hl,llen); } if(rlen > 0){ usezhCreate(t->right,zr,hr,rlen); } delete[] zl; delete[] zr; delete[] hl; delete[] hr; } } void minPath(element w = 0){ if(this){ w += data; if(left == NULL && right == NULL){ if(minweight > w){ minweight = w; minleaf = data; } return ; } left->minPath(w); right->minPath(w); } } }; int main(){ Tree *t = NULL; int z[10000],h[10000]; for(int i = 0;i < 10000;i++){ cin>>z[i]; if(cin.get() == ‘\n‘){ break; } } for(i = 0;i < 10000;i++){ cin>>h[i]; if(cin.get() == ‘\n‘){ break; } } t->usezhCreate(t,z,h,i + 1); t->minPath(); cout<<minleaf<<endl; return 0; } /* 7 8 11 3 5 16 12 18 8 3 11 7 16 18 12 5 3 2 1 4 5 7 6 3 1 2 5 6 7 4 */
二叉樹3(恢復二叉樹)