二叉树中和为某一值的路径

你快乐吗?

Posted by bbkgl on September 26, 2019

二叉树中和为某一值的路径

C++,简单的dfs,其实想不清楚为什么没有排序也能过。。。

代码:

/*
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>> FindPath(TreeNode* root,int expectNumber) {
        vector<vector<int>> ans;
        vector<int> path;
        if (!root) return ans;
        dfs(root, expectNumber, 0, path, ans);
        return ans;
    }
    
    void dfs(TreeNode *root, int &sum, int tsum, vector<int> &path, vector<vector<int>> &ans) {
        path.push_back(root->val);
        tsum += root->val;
        if (root->left)
            dfs(root->left, sum, tsum, path, ans);
        if (root->right)
            dfs(root->right, sum, tsum, path, ans);
        if (!root->left && !root->right)
            if (tsum == sum) 
                ans.push_back(path);
        path.pop_back();
    }
};