1、问题
给定一个二叉树与整数sum,找出所有从根节点到叶结点的路径,这些路 径上的节点值累加和为sum。
2、算法思路
- 从根节点深度遍历二叉树,先序遍历时,将该节点值存储至path栈中(vector实 现),使用 path_value累加节点值。
- 当遍历至叶结点时,检查path_value值是否为sum,若为sum,则将path push 进入result结果中。
- 在后续遍历时,将该节点值从path栈中弹出,path_value减去节点值。
3、代码实现
#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> > pathSum(TreeNode* root, int sum)
{
// 求以root为根结点的二叉树中,
// 哪些路径(从根结点到叶节点)的总和为sum.
vector< vector<int> > result; // 保存最终结果
vector<int> path; // 单条路径
int path_value = 0; // 路径和
preorder(root, sum, result, path, path_value);
return result;
}
private:
void preorder(TreeNode* node, int sum, vector< vector<int> >& result,
vector<int>& path, int& path_value)
{
if ( !node )
return;
// 针对于当前节点,先加
path_value += node->val;
// 并保存到路径path中
path.push_back(node->val);
// 判断一下
if (node -> left == NULL && node->right == NULL && path_value == sum)
{
result.push_back(path);
}
preorder(node->left, sum, result, path, path_value);
preorder(node->right, sum, result, path, path_value);
// 左右节点都处理完后
path_value -= node->val;
path.pop_back();
}
};
int main()
{
TreeNode a(5);
TreeNode b(4);
TreeNode c(8);
TreeNode d(11);
TreeNode e(13);
TreeNode f(4);
TreeNode g(7);
TreeNode h(2);
TreeNode i(5);
TreeNode j(1);
a.left = &b;
a.right = &c;
b.left = &d;
d.left = &g;
d.right = &h;
c.left = &e;
c.right = &f;
f.left = &i;
f.right = &j;
Solution S;
vector< vector<int> > result = S.pathSum(&a, 22);
cout << "total path number: " << result.size() << endl;
// 包装一下打印结果
cout << "[" << endl;
for (int i = 0; i < result.size(); i++)
{
cout << "\t[";
for (int j = 0; j < result[i].size(); j++)
{
if (j == (result[i].size() - 1))
cout << result[i][j];
else
cout << result[i][j] << ",";
}
if (i == (result.size() - 1))
cout << "]" << endl;
else
cout << "]," << endl;
}
cout << "]" << endl;
return 0;
}