UVA 548

这个思路比较清晰,依然是先建树,然后遍历

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
const int MAXN = 10005;
int inOrder[MAXN], postOrder[MAXN], nIndex;

class Node{
public:
    int data;
    Node *left;
    Node *right;
};

int nodeIndex;
Node node[MAXN];
vector<int>result;
vector<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]);
} 

// 由中序和后序遍历序列进行建树, 返回根结点指针
Node * InPostCreateTree(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=InPostCreateTree(mid,post,i);
	h->right=InPostCreateTree(mid+i+1,post+i,len-i-1);
	return h;
}

void dfs(Node *root, int n){
    if(!root->left && !root->right){
        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(){
    freopen("input.txt","r",stdin);
    while(~scanf("%d", &inOrder[0])){
        input();
        nodeIndex = 0;
        Node *root = InPostCreateTree(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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值