输入一颗二叉树,找到所有和为给定值的路径。路径是从根节点到叶节点的一条路径。
测试用例:
功能测试:完整的二叉树,只有左孩子(右孩子)的二叉树
特殊值测试:空指针,只有一个节点
#include<iostream>
#include<string.h>
#include<stack>
#include<vector>
using namespace std;
struct TreeNode{
int val;
TreeNode* leftchild;
TreeNode* rightchild;
};
void FindPath(TreeNode* root,int expectsum,vector<int> &path,int currentsum)
{
path.push_back(root->val);
currentsum+=root->val;
if(root->leftchild==nullptr&&root->rightchild==nullptr&&expectsum==currentsum)
{
for(int i=0;i<path.size();i++)
cout<<path[i]<<' ';
cout<<endl;
}
if(root->leftchild!=nullptr)
FindPath(root->leftchild,expectsum,path,currentsum);
if(root->rightchild!=nullptr)
FindPath(root->rightchild,expectsum,path,currentsum);
path.pop_back();
}
void FindPath(TreeNode* root,int expectsum)
{
if(root==nullptr)return;
vector<int> path;
int currensum=0;
FindPath(root,expectsum,path,currentsum);
}