要求
给定树,与路径和,判断是否存在从跟到叶子之和为给定值的路径。比如下图中,给定路径之和为22,存在路径<5,4,11,2>,因此返回true;否则返回false.
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 5
思路
递归,从跟到叶子判断,如果在叶子处剩下的给定值恰好为给定值,那么返回ture.
参考代码
/** * Definition for binary tree * 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) { if (root == NULL) return false; else if (root != NULL && root->left == NULL && root->right == NULL) { if (sum == root->val) return true; else return false; } else return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val); } };
扩展
求出所有符合条件的路径。例如,上题中返回<<5, 4, 11, 2>, <5, 8, 4, 5>>
参考代码
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void addPath(TreeNode *root, int sum, vector<int> tmp, vector<vector<int> > &rev) { if (root != NULL && root->left == NULL && root->right == NULL && root->val == sum) { tmp.push_back(root->val); rev.push_back(tmp); tmp.pop_back(); } if (root->left != NULL) { tmp.push_back(root->val); addPath(root->left, sum - root->val, tmp, rev); tmp.pop_back(); } if (root->right != NULL) { tmp.push_back(root->val); addPath(root->right, sum - root->val, tmp, rev); tmp.pop_back(); } } vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> > rev; if (root == NULL) return rev; vector<int> tmp; addPath(root, sum, tmp, rev); return rev; } };
本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/3710308.html,如需转载请自行联系原作者