面试题34:二叉树中和为某一值的路径
输入一棵二叉树和一个常数,打印出二叉树中节点值的和为输入整数的所有路径。
从树的根节点开始往下一直到叶结点所经过的节点形成一条路径。
力扣链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/submissions/
class Solution
{
public:
vector<vector<int>> pathSum(TreeNode* root, int target)
{
vector<vector<int>> ans;
if(root == NULL)
return ans;
vector<int> path;
int sum = 0;
FindPath(root, target, ans, path, sum);
return ans;
}
void FindPath(TreeNode* root, int target, vector<vector<int>>& ans, vector<int>& path, int sum)
{
if(root == NULL)
return;
path.push_back(root->val);
sum += root->val;
bool isLeaf = (root->left == NULL && root->right == NULL);
if(isLeaf && sum == target)
ans.push_back(path);
if(root->left)
FindPath(root->left, target, ans, path, sum);
if(root->right)
FindPath(root->right, target, ans, path, sum);
path.pop_back();
}
};
在前面的代码中,我们用标准模板库中的vector实现了一个栈来保存路径,每次都用push_back在路径的末尾添加节点,用pop_back在路径的末尾删除节点,这样就保证了栈的先入后出特性。这里没有直接用STL中的stack的原因是,在stack中只能得到栈顶元素,而我们打印路径的时候需要得到路径上的所有节点,因此在代码实现的时候std::stack不是最好的选择。