二叉树特训:树(UVA 548)二叉树的递归遍历

解题思路:首先根据中序遍历和后序遍历的结果还原二叉树,后序遍历的最后一个数字为根,在中序遍历中找到该根的位置,在其左边为左子树,右边为右子树,据此继续递归进行还原。还原完毕后通过DFS递归遍历,找到最小的边权和,最后打印结果。

题目大意:输入一个二叉树的中序和后序,输出一个叶子节点,该叶子节点到根的数值总和最小。

Sample Input 
3 2 1 4 5 7 6
3 1 2 5 6 7 4
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
255
255
Sample Output 
1
3
255

 

#include<cstdio>
#include<iostream>
#include<string.h>
using namespace std; 

struct node{
	char v;
	node *left;
	node *right;
}Tree[1000];

int loc;
char str1[1000],str2[1000];

node *creat()
{
	Tree[loc].right=Tree[loc].left=NULL;
	return &Tree[loc++];
}

node *build(int s1,int e1,int s2,int e2)
{
	node *ret=creat();
	ret->v=str2[e2];
	int countn;
	for(int i=s1;i<=e1;i++)
	{
		if(str1[i]==str2[e2])
		{
			countn=i;
		}
	}
	if(countn!=s1)
	{
		ret->left=build(s1,countn-1,s2,s2+countn-s1-1);
	}
	if(countn!=e1)
	{
		ret->right=build(countn+1,e1,s2+countn-s1,e2-1); 
	}
	return ret;
}

int maxn;
char maxnum;
void DFS(node *T,int sum)    //DFS遍历求得最小边权和 
{
	
	if(T->left==NULL&&T->right==NULL)
	{
		if(sum+T->v-'0'<maxn||(sum+T->v-'0'==maxn&&T->v<maxnum))
		{
			maxn=sum+T->v-'0';
			maxnum=T->v;
			//printf("%d %c\n",sum,maxnum);
		}
		return;
	}
	if(T->left!=NULL) DFS(T->left,sum+T->v-'0');
	if(T->right!=NULL) DFS(T->right,sum+T->v-'0');
}

int main()
{
	while(1)
	{
		loc=0;
		scanf("%s%s",str1,str2);
		int l1=strlen(str1)-1;
		int l2=strlen(str2)-1;
		node *T=build(0,l1,0,l2);
		maxn=123123123;
        maxnum='9';
		DFS(T,0);
		printf("%d\n",maxn);
		printf("%d\n",maxnum-'0');
	}
	
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值