1. 程式人生 > >輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑(劍指offer)

輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑(劍指offer)

      解題思路:遍歷二叉樹,採用遞迴的方法,將滿足條件的路徑壓入一維陣列當中,注意當找到滿足條件的路徑時,先將陣列壓入二維陣列,然後將一維陣列中的每個元數彈出,以存放新的路徑。

/*

struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
    vector<vector<int>> result;
    vector<int>temp;
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        if(root != NULL)
        findOnePath(root,expectNumber);
        return result;
    }
    
    void findOnePath(TreeNode* root,int expectNumber){
        temp.push_back(root->val);
        if(expectNumber - root->val==0 && root->right ==NULL && root->left == NULL)
            result.push_back(temp);
        if(root->left != NULL)findOnePath(root->left,expectNumber-root->val);
        if(root->right != NULL)findOnePath(root->right,expectNumber-root->val);
        temp.pop_back();
        
    }
};