考察二叉树的前序遍历。
C++版本
#include <iostream>
#include <vector>
#include <stack>
#include <cstring>
#include <string>
#include <queue>
#include <algorithm>
#include "TreeNode.h"
using namespace std;
// vector<int>& path传递的是引用,会修改实参的值;也可以传递指针vector<int>* path
void FindPath(TreeNode* root, int expectedSum, vector<int>& path, int currentSum, vector<vector<int>>& ans){
currentSum= currentSum + root->val;
path.push_back(root->val);
// 如果是叶子节点,并且路径上节点值的和等于输入的值,则添加这条路径
bool isLeaf = root->left == nullptr && root->right == nullptr;
if(isLeaf && currentSum == expectedSum){
// 添加一行路径
ans.push_back(vector<int>());
cout<<"A path is found:";
for(int i = 0; i < path.size(); i++){
cout<<path[i]<<" ";
ans[ans.size() - 1].push_back(path[i]);
}
cout<<endl;
}
// 如果不是叶节点,则遍历它的子节点
if(root->left != nullptr)
FindPath(root->left, expectedSum, path, currentSum, ans);
if(root->right != nullptr)
FindPath(root->right, expectedSum, path, currentSum, ans);
path.pop_back();
}
vector<vector<int>> FindPath(TreeNode* root,int expectNumber) {
vector<vector<int>> ans;
if(root == nullptr)
return ans;
vector<int> path;
int currentSum = 0;
FindPath(root, expectNumber, path, currentSum, ans);
return ans;
}
int main()
{
return 0;
}