112. Path Sum

来源:互联网 发布:表格中数据单位转换 编辑:程序博客网 时间:2024/05/16 08:47

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5             / \            4   8           /   / \          11  13  4         /  \      \        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

solution:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool hasPathSum(TreeNode* root, int sum) {        vector<int> ps;        int flag;        traverse(root, sum, flag, ps);        return flag==1;    }    void traverse(TreeNode* root, int sum, int &flag, vector<int> ps){        if(!root) return;        if(ps.size()==0) ps.push_back(0);        ps[ps.size()-1] += root->val;                    if(!root->left&&!root->right) {            if(ps[ps.size()-1]==sum) {flag=1; return;}            else return;        }        if(root->left&&!root->right) traverse(root->left, sum, flag, ps);        if(root->right&&!root->left) traverse(root->right, sum, flag, ps);        if(root->left&&root->right){            int tmp = ps[ps.size()-1];            traverse(root->left, sum, flag, ps);            ps.push_back(tmp);            traverse(root->right, sum, flag, ps);        }    }};
心得:思路比较简单,运行时间较长,搜了一下别人的方法 http://blog.csdn.net/booirror/article/details/42680111 这个方法很好,我自己一直纠结于加确没有考虑减,导致代码冗长

运行时间:慢

0 0
原创粉丝点击