标签:
// 24.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <vector> using namespace::std; 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 exp) { vector<vector<int>> retVec; if (root == NULL)return retVec; vector<int> path; int cur = 0; recursive(root, retVec, path, exp, cur); return retVec; } void recursive(TreeNode* root, vector<vector<int>>& retVec, vector<int>& path, int sum, int& cur) { path.push_back(root->val); cur = cur + root->val; bool isLeaf = (root->left == NULL) && (root->right == NULL); if (isLeaf && sum == cur) { retVec.push_back(path); } if (root->left != NULL) { recursive(root->left, retVec, path, sum, cur); } if (root->right != NULL) { recursive(root->right, retVec, path, sum, cur); } path.pop_back(); cur -= root->val; } }; int _tmain(int argc, _TCHAR* argv[]) { TreeNode* root = new TreeNode(10); TreeNode* rootLeft = new TreeNode(5); TreeNode* rootRight = new TreeNode(12); TreeNode* leftLeft = new TreeNode(4); TreeNode* leftRight = new TreeNode(7); root->left = rootLeft; root->right = rootRight; rootLeft->left = leftLeft; rootLeft->right = leftRight; Solution s; s.FindPath(NULL, 22); return 0; }
标签:
原文地址:http://blog.csdn.net/chengonghao/article/details/51335046