uva 112 - Tree Summing

// uva 112 - Tree Summing
// 题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=104&page=show_problem&problem=48
// 题目大意: 给一个整数n和一颗树,求是否存在一条从根节点到叶节点的和等于这个整数
#include <cstdio>
#include <cstring>
#include <iostream>
#include <stack>
#include <cctype>
using namespace std;
int nN, nBuf;
char chBuf;
struct Node{
	bool negative;
	int val;
	bool notEmpty;
	Node *left, *right;
};
stack<char> sta;
stack<Node*> staNode;
Node *head, *nowNode;
bool flag;
void Solve();
void getSum(Node*, int);
void Delete(Node*);
int main(){
	while(cin >> nN){
		while((chBuf = getchar()) != '('){}
		sta.push(chBuf);
		nowNode = new Node();
		head = nowNode;
		while(sta.size()){
			chBuf = getchar();
			if(isdigit(chBuf)){
				if(nowNode->notEmpty == false){
					nowNode->val = chBuf - '0';
					nowNode->notEmpty = true;
				}else{
					nowNode->val *= 10;
					nowNode->val += chBuf - '0';
				}
			}else if(chBuf == '('){
				sta.push(chBuf);
				Node* newNode = new Node();
				if(nowNode->left == NULL){
					nowNode->left = newNode;
				}else{
					nowNode->right = newNode;
				}
				staNode.push(nowNode);
				nowNode = newNode;
			}else if(chBuf == '-'){
				nowNode->negative ^= 1;		
			}else if(chBuf == ')'){
				sta.pop();
				if(sta.size()){
					nowNode = staNode.top();
					staNode.pop();
				}
			}
		}
		Solve();
		
 	}
	return 0;
}
void Solve(){
	flag = false;
	if(head->notEmpty)
		getSum(head, 0);
	if(flag)
		cout << "yes" << endl;
	else
		cout << "no"  << endl;
	Delete(head);
}
void getSum(Node* ptr, int sum){
	if(ptr->negative)
		sum -= ptr->val;
	else
		sum += ptr->val; 
	if(ptr->left != NULL && ptr->left->notEmpty)
		getSum(ptr->left, sum);	
	if(ptr->right != NULL && ptr->right->notEmpty)
		getSum(ptr->right, sum);
	if(ptr->left==NULL && ptr->right == NULL || !ptr->left->notEmpty && !ptr->right->notEmpty){
		if(sum == nN)
			flag = true;
	}
}
void Delete(Node* root){
	if(root->notEmpty){
		Delete(root->left);
		Delete(root->right);
	}
	delete(root);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值