https://oj.leetcode.com/problems/path-sum-ii/
树的深搜,从根到叶子,并记录符合条件的路径。
注意参数的传递,是否需要使用引用。
#include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector<vector<int> > ans; vector<vector<int> > pathSum(TreeNode *root, int sum) { ans.clear(); if(root == NULL) return ans; vector<int> ansPiece; hasPathSum(root,sum,ansPiece); return ans; } void hasPathSum(TreeNode *root, int sum, vector<int> ansPiece) { //null if(root == NULL ) return ; //leaf node if(root->left == NULL && root->right == NULL && root->val == sum) { ansPiece.push_back(root->val); vector<int> _ansPiece = ansPiece; ans.push_back(_ansPiece); return ; } if(root->left == NULL && root->right == NULL) return ; //not leaf node if(root->left ||root->right) { ansPiece.push_back(root->val); if(root->left) hasPathSum(root->left, sum - root->val,ansPiece); if(root->right) hasPathSum(root->right, sum-root->val, ansPiece); } return; } }; int main() { TreeNode *n1 = new TreeNode(1); TreeNode *n2 = new TreeNode(-2); TreeNode *n3 = new TreeNode(-3); TreeNode *n4 = new TreeNode(1); TreeNode *n5 = new TreeNode(3); TreeNode *n6 = new TreeNode(-2); TreeNode *n7 = new TreeNode(4); TreeNode *n8 = new TreeNode(4); n1->left = n2; n1->right = n3; n2->left = n4; n2->right = n5; n3->left = n6; n3->right = n8; n4->left = n7; class Solution myS; myS.pathSum(n1,2); return 0; }