Topic:
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 and
sum = 22,
5 / 4 8 / / / 4 / \ / 7 2 5 1
Return
[ [5,4,11,2], [5,8,4,5]]
idea: construct an auxiliary function. An auxiliary function is a deep search recursive function. Recursive termination conditions, similar to path sum, when the current node is a leaf node, and the current node value equals the sum value, first push the current node value into TMP, and then return. If the current node is not empty, press the current result into TMP and then recursively Saozi the right subtree to find all possible combinations.
Attention:
1. Note that only the left and right child nodes are present, and the helper function is called recursively, searching the left and right subtrees.
Need to determine whether there are left and right nodes, there is no recursive call to the if (root->left) pathsum_helper (Root->left, Newsum, TMP, ret); if (root->right) pathsum_helper (root->right, Newsum, TMP, ret);
2. When the current node is judged to meet the iteration termination criteria, first push the current node value into the array before returning the result. (There is no push current node value in the previous layer call)
/If the node at this point is a leaf node and is in accordance with the sum condition, first push into TMP and return. if (!root->left &&!root->right && root->val = = sum) { tmp.push_back (root->val); Ret.push_back (TMP); return; }
AC Code:
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {public:vector<vector<int> > Pathsum (TreeNode *root, int sum) {VECTOR<VECTOR&L t;int> > ret; vector<int> tmp; if (root = NULL) return ret; Pathsum_helper (root, SUM, TMP, ret); return ret; } private:void Pathsum_helper (treenode* root, int sum, vector<int> tmp, vector<vector<int>>& RET) {//If the node at this point is a leaf node and is in accordance with the sum condition, first push into TMP and return. if (!root->left &&!root->right && root->val = = sum) {Tmp.push_back (Root->va L); Ret.push_back (TMP); Return } if (root = NULL) {tmp.push_back (root->val); int newsum = sum-root->val; Need to determine if there are left and right nodes, no recursive call if (root->left) Pathsum_helper (Root->left, Newsum, TMP, ret); if (root->right) pathsum_helper (root->right, Newsum, TMP, ret); } return; }};
[C + +] leetcode:91 Path Sum II