首页 > 代码库 > Leetcode Path Sum
Leetcode Path Sum
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.
递归实现
从树根开始判断
- 如果当前是叶子节点等于剩余和,那么程序返回真
- 如果当前节点为空,则放回false
- 除了以上情况,返回递归调用左右子节点的结果或值,并且传入剩余和扣除当前节点值后的值
class Solution {public: bool hasPathSum(TreeNode *root, int sum) { if(root == NULL) return false; if(root->left == NULL && root->right == NULL && sum == root->val) return true; else return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right, sum-root->val); }};
class Solution {public: bool hasPathSum(TreeNode *root, int sum) { if(root == NULL) return false; if(root->left == NULL && root->right == NULL) return sum == root->val; sum-=root->val; return hasPathSum(root->left,sum) || hasPathSum(root->right, sum); }};
非递归遍历(根据层次遍历实现即可)
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */#include <iostream>#include <queue>using namespace std;struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode(int x): val(x), left(NULL),right(NULL){}};struct TreeNodeSum{ TreeNode *node; int sum; TreeNodeSum(TreeNode* node_, int sum_ ):node(node_),sum(sum_){}};bool hasPathSum(TreeNode *root, int sum) { if(root == NULL) return false; queue<TreeNodeSum *> que; que.push(new TreeNodeSum(root,root->val)); int res = 0; while(!que.empty()){ TreeNodeSum *tmp = que.front();que.pop(); TreeNode *node = tmp->node; cout<<node->val<<endl; if(!node->left && !node->right && tmp->sum == sum) return true; if(node->left){ TreeNodeSum *nodeSum = new TreeNodeSum(node->left,node->left->val+tmp->sum); que.push(nodeSum); } if(node->right ){ TreeNodeSum *nodeSum = new TreeNodeSum(node->right,node->right->val+tmp->sum); que.push(nodeSum); } } return false;}int main(){ TreeNode *root = new TreeNode(1); TreeNode *root1 = new TreeNode(-2); TreeNode *root2 = new TreeNode(-3); TreeNode *root3 = new TreeNode(1); TreeNode *root4 = new TreeNode(3); TreeNode *root5 = new TreeNode(-2); TreeNode *root6 = new TreeNode(-1); root->left = root1; root->right = root2; root1->left = root3; root1->right = root4; root2->left = root5; root3->left = root6; cout<<hasPathSum(root,-1)<<endl;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。