`
Jianquan
  • 浏览: 18937 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Uva 112 Tree Summing 二叉树

    博客分类:
  • UVa
阅读更多
题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=48
主要思路:这道题目的难点在于如何把题目所给的输入数据转换成一棵树。首先定义一个字符型的变量c,再定义一个整型的变量num。因为开始一定是'(',所以先输入c(cin>>c;),然后判断,如果是'(',那么再输入num(cin>>num;),这里加一个判断,如果说cin>>num输入正常,那么输入的是一个数;如果说输入异常,那么输入的是')'。这样就可以把括号的输入和数字的输入分开了。然后就是入栈、出栈,转换成二叉树,然后再dfs。
具体代码:
#include<iostream>
#include<cstdlib>
#include<stack>
using namespace std;

struct Node
{
	int value;
	Node *left,*right;
};

int I;
bool dfs(Node *n,int sum)
{
	sum+=n->value;
	if(!n->left&&!n->right&&sum==I) return 1;
	if(n->left&&dfs(n->left,sum)) return 1;
	if(n->right&&dfs(n->right,sum)) return 1;
	return 0;
}		
int main()
{
	//freopen("in.txt","r",stdin);
	int num;
	char c;
	stack<Node *> s_Node;
	while(cin>>I)
	{
		while(!s_Node.empty()) s_Node.pop();
		int left_num=0,right_num=0;//左右括号的数目
		do
		{
			cin>>c;
			if(c=='(')
			{
				if(!(cin>>num))//如果输入异常,说明是')'
				{
					cin.clear();
					cin>>c;
					Node *tmp=NULL;
					s_Node.push(tmp);
				}
				else
				{
					left_num++;
					Node *tmp=(Node *)malloc(sizeof(Node));
					tmp->value=num;
					tmp->left=tmp->right=NULL;
					s_Node.push(tmp);
				}
			}
			else
			{
				right_num++;
				Node *tmp,*left,*right;
				right=s_Node.top();
				s_Node.pop();
				left=s_Node.top();
				s_Node.pop();
				tmp=s_Node.top();
				tmp->left=left;
				tmp->right=right;
			}
		}while(left_num>right_num);
		Node *root=s_Node.top();
		s_Node.pop();
		if(root)
		{
			if(dfs(root,0))
				cout<<"yes"<<endl;
			else
				cout<<"no"<<endl;
		}
		else
			cout<<"no"<<endl;
	}
	return 0;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics