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 andsum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1return true, as there exist a root-to-leaf path
5->4->11->2
which sum is 22.
设置个path向量,用于存储路径,由于有求和操作,使用vector比较方便,遇到叶子结点时,计算和是否=sum,不是叶子结点遍历左右非空的子树,由于是求是否含有路径,所以左右子树只要有一个为true即可返回true.class Solution { public: bool hasPathSum(TreeNode *root, int sum) { if(root == NULL)return false; vector<int> path; return hasPathOrNot(root, sum, path); } bool hasPathOrNot(TreeNode *root, int sum, vector<int> &path) { int value = root->val; path.push_back(value); if(root->left == NULL && root->right == NULL) { int total = 0; for(int i = 0;i<path.size();i++) { total += path[i]; } path.pop_back(); if(total == sum) return true; else return false; } bool pleft=false, pright=false; if(root->left != NULL) pleft = hasPathOrNot(root->left, sum, path); if(root->right != NULL) pright = hasPathOrNot(root->right, sum, path); path.pop_back(); return pleft||pright; } };
Path Sum路径求和
最新推荐文章于 2022-07-23 18:59:28 发布