题目描述:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
分析:路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
用递归的思想去把和分解
代码实现:
#include <iostream>
#include <vector>
using namespace std;typedef struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
}Node;class Solution {
public:vector<vector<int> > buffer;vector<int> tmp;vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {if(root==NULL)return buffer;tmp.push_back(root->val);if((expectNumber-root->val)==0 && root->left==NULL && root->right==NULL){buffer.push_back(tmp);}FindPath(root->left,expectNumber-root->val);FindPath(root->right,expectNumber-root->val);if(tmp.size()!=0)tmp.pop_back();return buffer;}
};int main()
{Node *tmp ;Node* root = new Node(10);tmp = new Node(5);root->left = tmp ;tmp = new Node(12);root->right = tmp;tmp = new Node(4);root->left->left = tmp;tmp = new Node(7);root->left->right = tmp;vector<vector<int>> ret;Solution s;ret = s.FindPath(root,22); return 0;
}