POJ 1145:Tree Summing (二叉树路径和)

1145:Tree Summing
查看提交统计提示提问
总时间限制: 1000ms 内存限制: 65536kB
描述
LISP was one of the earliest high-level programming languages and, with FORTRAN, is one of the oldest languages currently being used. Lists, which are the fundamental data structures in LISP, can easily be adapted to represent other important data structures such as trees.

This problem deals with determining whether binary trees represented as LISP S-expressions possess a certain property.
Given a binary tree of integers, you are to write a program that determines whether there exists a root-to-leaf path whose nodes sum to a specified integer. For example, in the tree shown below there are exactly four root-to-leaf paths. The sums of the paths are 27, 22, 26, and 18.

Binary trees are represented in the input file as LISP S-expressions having the following form.

empty tree ::= ()

tree ::= empty tree (integer tree tree)

The tree diagrammed above is represented by the expression (5 (4 (11 (7 () ()) (2 () ()) ) ()) (8 (13 () ()) (4 () (1 () ()) ) ) )

Note that with this formulation all leaves of a tree are of the form (integer () () )

Since an empty tree has no root-to-leaf paths, any query as to whether a path exists whose sum is a specified integer in an empty tree must be answered negatively.
输入
The input consists of a sequence of test cases in the form of integer/tree pairs. Each test case consists of an integer followed by one or more spaces followed by a binary tree formatted as an S-expression as described above. All binary tree S-expressions will be valid, but expressions may be spread over several lines and may contain spaces. There will be one or more test cases in an input file, and input is terminated by end-of-file.
输出
There should be one line of output for each test case (integer/tree pair) in the input file. For each pair I,T (I represents the integer, T represents the tree) the output is the string yes if there is a root-to-leaf path in T whose sum is I and no if there is no path in T whose sum is I.
样例输入
22 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
20 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
10 (3
(2 (4 () () )
(8 () () ) )
(1 (6 () () )
(4 () () ) ) )
5 ()
样例输出
yes
no
yes
no
来源
Duke Internet Programming Contest 1992,UVA 112

这道题坑很多,wa了很多次,主要的坑都在代码的注释里写了。

主要过程就是一个递归建立二叉树的过程,同时计算一个二叉树到叶子节点的路径和。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <unordered_map>
#include <string>
#include <math.h>
typedef long long ll;

using namespace std;

struct node
{
    int val;
    node *left;
    node *right;
};

bool flag = false;
int target;

void get_tree_sum(node *root, int pre_sum)
{
    if (flag) //如果已经找到一条路经  就不需要后续计算了。
    {
        return;
    }
    if (root->left == NULL && root->right == NULL) //只有左右子树都是空的节点才是叶子节点,这里很容易写成在空节点处判断,就会出错。 
                                                //例如(4(1()())())可能在某个到4的路径和等于target,而实际上这个路径没有到叶子节点。
    {
        if (pre_sum + root->val == target)
        {
            flag = true;
        }
        return;
    }
    if (root->left != NULL)
    {
        get_tree_sum(root->left, pre_sum + root->val);
    }
    if (root->right != NULL)
    {
        get_tree_sum(root->right, pre_sum + root->val);
    }

    return;
}

node *build_tree(string tree)
{
    if (tree.size() == 2)
    {
        return NULL;
    }

    node *cur_root = (node *)malloc(sizeof(node));
    int j = 1; //因为第一个字符一定是( 所以从第二个字符开始判断。
    int cur = 0;

    // 树的值可能是负数,这个很坑,很大概率在这里WA掉
    int inverse = 1;
    if (tree[j] == '-')
    {
        inverse = -1;
        j++;
    }

    //获取当前的根节点的值
    while (tree[j] != '(' && tree[j] != ')')
    {
        cur = cur * 10 + (tree[j] - '0');
        j++;
    }
    cur = cur * inverse;
    cur_root->val = cur;

    //根据括号数来判断哪些字符串是左子树,哪些是右子树
    int l = 0;
    string left;
    string right;
    for (int i = j; i < tree.size() - 1; i++)
    {
        if (tree[i] == '(')
        {
            l++;
        }
        else if (tree[i] == ')')
        {
            l--;
        }
        if (l == 0) //左右括号数完全匹配的时候说明是一颗完整的子树
        {
            left = tree.substr(j, i - j + 1);
            int right_len = (tree.size() - 2) - (i + 1) + 1;
            right = tree.substr(i + 1, right_len);
            break;
        }
    }
    cur_root->left = build_tree(left); //递归构建左子树
    cur_root->right = build_tree(right); //递归构建右子树
    return cur_root;
}

int main()
{

    while (~scanf("%d", &target))
    {
        flag = false;
        int l = 1;
        char c;
        string tree;
        cin >> c;
        tree += c;
        if (c == '(')
        {
            l++;
        }
        while (l > 1)
        {
            cin >> c;
            tree += c;
            if (c == '(')
                l++;
            else if (c == ')')
                l--;
            else
                continue;
        }
        // cout << "=========" << tree << endl;

        node *root = build_tree(tree);
        if (root == NULL) //这里也是一个坑,如果是空树的话一定要输出no,这里需要单独判断,否则0 (0()())这个case会返回yes,
        {
            cout << "no" << endl;
        }
        else
        {
            get_tree_sum(root, 0);
            if (flag)
            {
                cout << "yes" << endl;
            }
            else
            {
                cout << "no" << endl;
            }
        }
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值