UVA 548 樹 ( 從中序和後續回複二叉樹)

來源:互聯網
上載者:User

分析:由中序,後序轉為先序。要清楚三種遍曆方式,能用先序和中序轉為後序,由後序和中序轉為前序



#include<iostream>#include<cstdio>#include<cstring>#include<vector>using namespace std;const int maxn=10005;int inOrder[maxn], postOrder[maxn], nIndex;struct Node{    int data;    struct Node *left;    struct Node *right;};int nodeIndex;struct Node node[maxn];vector<int>result;vector<struct Node*>pResult;bool flag;int ans;inline Node* NewNode()//建立節點{    node[nodeIndex].left = NULL;    node[nodeIndex].right = NULL;    return &node[nodeIndex++];}inline void input(){    nIndex=1;    while(getchar()!='\n')        scanf("%d", &inOrder[nIndex++]);    for(int i=0; i<nIndex; ++i)        scanf("%d", &postOrder[i]);}struct Node* CreateTree(int *mid,int *post,int len)
{    if(len == 0)        return NULL;    int i=len-1;    while(post[len-1] != mid[i])//後序的最後為根結點,依次遞迴        --i;    Node *h=NewNode();    h->data=post[len-1];    h->left=CreateTree(mid,post,i);    h->right=CreateTree(mid+i+1,post+i,len-i-1);    return h;}void dfs(Node *root, int n){    if(!root->left&&!root->right)//DFS遍曆整個樹    {        result.push_back(n+root->data);        pResult.push_back(root);        return;    }    if(root->left)  dfs(root->left, n+root->data);    if(root->right) dfs(root->right, n+root->data);}int main(){    while(scanf("%d", &inOrder[0])!=EOF)    {        input();        nodeIndex = 0;        Node *root =CreateTree(inOrder, postOrder, nIndex);        result.clear();        pResult.clear();        dfs(root, 0);        int minPos = 0;        for(int i=1; i<result.size(); ++i)            if(result[i] < result[minPos]) minPos=i;        printf("%d\n",pResult[minPos]->data);    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.