Path sum
OJ: https://oj.leetcode.com/problems/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 andsum = 22
,
5 / 4 8 / / 11 13 4 / \ 7 2 1
Return true, as there exist a root-to-leaf path5->4->11->2
Which sum is 22.
Idea: traverse in sequence. If the current node is empty, false is returned. If the current node is not empty, the value is added. If the node is a leaf node, it is judged once.
Note: The path is not the path and, but the path to the leaf node and. For example:{1, 2} 1 returns: false
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */bool judge(TreeNode *root, int curSum, int& sum) { if(root == NULL) return false; curSum += root->val; if(!root->left && !root->right) return curSum == sum; return judge(root->left, curSum, sum) || judge(root->right, curSum, sum);} class Solution {public: bool hasPathSum(TreeNode *root, int sum) { return judge(root, 0, sum); }};
Path sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree andsum = 22
,
5 / 4 8 / / 11 13 4 / \ / 7 2 5 1
Return
[,], [,]
Same idea: Just write down the path.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */void getPath(TreeNode *root, int curSum, int& sum, vector<vector<int> > &pathSet, vector<int> &path) { if(root == NULL) return; curSum += root->val; path.push_back(root->val); if(!root->left && !root->right && curSum == sum) pathSet.push_back(path); getPath(root->left, curSum, sum, pathSet, path); getPath(root->right, curSum, sum, pathSet, path); path.pop_back();}class Solution {public: vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> >pathSet; vector<int> path; getPath(root, 0, sum, pathSet, path); return pathSet; }};
32. Path sum & Path sum II