www

导航

二叉树和为某一值的路径

struct TreeNode
{
    TreeNode *left;
    TreeNode *right;
    int val;
};

void helper(TreeNode *root, vector<int> &path, int currentsum, int sum)
{
    path.push_back(root->val);
    currentsum += root->val;
    bool isleaf = root->left == nullptr&&root->right == nullptr;
    if (currentsum == sum&&isleaf)
    {
        for (int i : path)
        {
            cout << i << " ";
        }
        cout << endl;
    }
    if (root->left != nullptr)
    {
        helper(root->left, path, currentsum, sum);
    }
    if (root->right != nullptr)
    {
        helper(root->right, path, currentsum, sum);
    }
    path.pop_back();
}

void FindPath(TreeNode *root, int sum)
{
    if (root == nullptr)
        return;
    vector<int> path;
    int currentsum = 0;
    helper(root, path, currentsum, sum);
}

 

posted on 2017-09-21 21:09  www_practice  阅读(133)  评论(0编辑  收藏  举报