UVA 548 树 ( 从中序和后续回复二叉树)

分析:由中序,后序转为先序。要清楚三种遍历方式,能用先序和中序转为后序,由后序和中序转为前序



#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;
}

你可能感兴趣的:(树,uva,548,从中序和后续回复)