二叉树中和为某一值的路经

输入一颗二叉树和一个整数,找到二叉树中节点值得和为输入整数的所有路经。从根节点开始到叶子结点为一路经。

思路:二叉树中,首先遍历根节点的是前序遍历。因为要从根节点开始,所以首先考虑前序遍历。在这个遍历的过程中,会从根节点开始,由左至右依次遍历二叉树的每一条路经。遍历到叶子结点时检查路经中的节点之和是否达到所求的节点值。

还是看代码最清晰:所以直接上代码吧

//二叉树中 和为某一值的路经
struct TreeNode
{
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :val(x), left(NULL), right(NULL){}
};
void push_res(vector<vector<int>> &res, TreeNode* root, vector<int> &path, int cur, int num)
{
	cur += root->val;
	path.push_back(root->val);
	if (root->left == NULL && root->right == NULL &&cur == num)
		res.push_back(path);
	if (root->left)
		push_res(res, root->left, path, cur, num);
	if (root->right)
		push_res(res, root->right, path, cur, num);
	path.pop_back();
}
vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {
	vector<vector<int>> res;
	if (root == NULL)
		return res;
	vector<int> path;
	int cur = 0;
	push_res(res, root, path, cur, expectNumber);
	return res;
}
原文地址:https://www.cnblogs.com/weiyi-mgh/p/6656814.html