題目:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:sum
= 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
思路:構造一個輔助函數。輔助函數是一個深度搜索遞歸函數。遞歸終止條件,和Path Sum類似,當當前節點是葉子結點,並且當前節點值等於sum值,先把當前節點值push進tmp,再返回。如果當前節點非空,將當前結果壓進tmp中,再接下來遞歸其左子樹和右子樹,尋找所有的可能組合。
Attention:
1. 注意只有存在左右孩子結點時,才遞歸調用輔助函數,搜索左右子樹。
//需要判斷是否有左右結點,沒有就不遞歸調用了 if(root->left) pathSum_helper(root->left, newSum, tmp, ret); if(root->right) pathSum_helper(root->right, newSum, tmp, ret);
2. 當判斷當前節點符合迭代終止條件後,首先應先把當前節點值push進數組,再返回結果。(上一層調用中並沒有push當前節點值)
/如果此時的節點就是葉子節點,並且符合sum條件,先push進tmp,再返回。 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; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector> pathSum(TreeNode *root, int sum) { vector > ret; vector tmp; if(root == NULL) return ret; pathSum_helper(root, sum, tmp, ret); return ret; } private: void pathSum_helper(TreeNode* root, int sum, vector tmp, vector >& ret) { //如果此時的節點就是葉子節點,並且符合sum條件,先push進tmp,再返回。 if(!root->left && !root->right && root->val == sum) { tmp.push_back(root->val); ret.push_back(tmp); return; } if(root != NULL) { tmp.push_back(root->val); int newSum = sum - root->val; //需要判斷是否有左右結點,沒有就不遞歸調用了 if(root->left) pathSum_helper(root->left, newSum, tmp, ret); if(root->right) pathSum_helper(root->right, newSum, tmp, ret); } return; } };