#include <iostream> #include <vector> #include <iterator> #include <algorithm> using namespace std; vector<int> result; struct Node { Node(int i = 0, Node *pl = NULL, Node *pr = NULL) : data(i), left(pl), right(pr) {} int data; Node *left; Node *right; }; Node* Construct() { Node *node4 = new Node(7); Node *node3 = new Node(4); Node *node2 = new Node(12); Node *node1 = new Node(5, node3, node4); Node *root = new Node(10, node1, node2); return root; } void print() { copy(result.begin(), result.end(), ostream_iterator<int>(cout, " ")); cout << endl; } void PrintSum(Node *root, int sum) { if(root == NULL) return; result.push_back(root->data); if(root->left == NULL && root->right == NULL && root->data == sum) { print(); } PrintSum(root->left, sum - root->data); PrintSum(root->right, sum - root->data); result.pop_back(); } void main() { Node *root = Construct(); PrintSum(root, 22); } 如果元素全部是整数,没有负数,那么算法还可以改进,避免多余的运算 void findAllPath(Node *root, int sum) { if(sum < 0 || root == NULL) return; if(root->left == NULL && root->right == NULL && sum == root->item) { nvec.push_back(root); print(); nvec.pop_back(); return; } nvec.push_back(root); findAllPath(root->left, sum - root->item); findAllPath(root->right, sum - root->item); nvec.pop_back(); }