Binary tree? And the path!
Title
Given a binary tree and a target and to find all paths from the root node to the leaf node is equal to the sum of the path and the given target.
Description: leaf node is a node has no child nodes.
Examples
Example:
Given the following binary tree, and the target and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Returns:
[
[5,4,11,2],
[5,8,4,5]
]
Topic analysis
- Goal: to find all paths starting from the root to leaf node ⇒ its junction equals the target value
- Find the path from the root to leaf node ⇒ recursive solution
- If the node is equal to the sum of the target value path ⇒ Add
Problem-solving ideas
variable | effect |
---|---|
find() | Seeking the path function |
process
- ⇒ Add current node to update the path of the node and
- Analyzing the node is equal to the sum of the target value and the current node is a leaf node if the condition is satisfied ⇒ add the path to the answer
- If the left subtree is not empty ⇒ update left child node to the current node, repeat 2,3,4
- If the right subtree is not empty ⇒ update right child nodes for the current node, repeat 2,3,4
code show as below
void find(TreeNode*root, int add, int sum, vector<int> path, vector<vector<int>> &ans)
{
add += root->val; //更新结点和
path.push_back(root->val); //当前结点加入路径
if(add == sum&&!root->left&&!root->right) ans.push_back(path);
if(root->left) find(root->left,add,sum,path,ans);
if(root->right) find(root->right,add,sum,path,ans);
}
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if(!root) return{};
vector<vector<int>> ans;
vector<int> path;
int add =0;
find(root, add, sum, path, ans);
return ans;
}
};