二叉树和为某一值的路径

输入一颗二叉树,找到所有和为给定值的路径。路径是从根节点到叶节点的一条路径。

测试用例:

功能测试:完整的二叉树,只有左孩子(右孩子)的二叉树

特殊值测试:空指针,只有一个节点

#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);
}

猜你喜欢

转载自blog.csdn.net/qq_36162275/article/details/87910811