二叉树中和为某一值的路径 题目描述 我的代码

原文地址:https://www.jianshu.com/p/480b03915b99

时间限制:1秒 空间限制:32768K

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

我的代码

/*
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>> res;
        vector<int> trace;
        if(root==nullptr)
            return res;
        FindPathCore(res,trace,root,expectNumber);
        return res;
    }
    void FindPathCore(vector<vector<int>> &res, vector<int> &trace, 
                  TreeNode* root,int expectNumber){
        trace.push_back(root->val);
        if(root->val==expectNumber && root->left==nullptr && root->right==nullptr)
            res.push_back(trace);
        if(root->left)
            FindPathCore(res,trace,root->left,expectNumber-root->val);
        if(root->right)
            FindPathCore(res,trace,root->right,expectNumber-root->val);
        trace.pop_back();
        return;
    }
};

运行时间:5ms
占用内存:600k