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:
    //DFS
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        vector<vector<int> > ans;
        if (root == nullptr)
            return ans;
        vector<int> path;
        dfs(ans, path, root, 0, expectNumber);
        return ans;
    }
private:
    void dfs(vector<vector<int> > &ans, vector<int> &path, TreeNode* p, int sum, int n)
    {
        path.push_back(p->val);
        sum += p->val;
        //到達葉節點時檢查節點和是否等於給定值
        if (p->left == nullptr && p->right == nullptr && sum == n)
            ans.push_back(path);
        if(p->left != nullptr)
            dfs(ans, path, p->left, sum, n);
        if(p->right != nullptr)
            dfs(ans, path, p->right, sum, n);
        //最後記得彈出路徑點
        path.pop_back();
    }
};