二叉树中和为某一值的路径 ----《剑指offer》面试题25

题目

  输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

在这里插入图片描述

思路

  当用前序遍历的方式访问到某一结点时,我们把结点添加到路径上,并累加该结点的值。如果该结点为叶结点并且路径中结点值的和刚好等于输入的整数,则当前的路径符合要求,将它打印出来。如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数将自动回到它的父结点。因此在函数退出前,要在路径上删除当前结点,并减去当前结点的值,以确保返回父结点的路径刚好是从根结点到父结点的路径。

代码

#include <iostream>
#include <vector>
using  namespace std;

struct BinaryTreeNode
{
    int m_nValue;
    BinaryTreeNode* m_pLeft;
    BinaryTreeNode* m_pRight;
};

void FindPath
    (
        BinaryTreeNode* pRoot,
        int expectedSum,
        std::vector<int>& path,
        int& currentSum
    )
{
    currentSum += pRoot->m_nValue;
    path.push_back(pRoot->m_nValue);

    //  如果是叶子结点,并且路径结点的和等于输入的值
    //  打印出这条路径
    bool isLeaf = pRoot->m_pLeft == nullptr && pRoot->m_pRight == nullptr;
    if(currentSum == expectedSum && isLeaf)
    {
        cout << "A path is found: ";
        for (auto item : path)
        {
            cout << item << "\t";
        }
        cout << endl;
    }

    //  如果不是结点,则遍历它的子结点
    if (pRoot->m_pLeft != nullptr)
        FindPath(pRoot->m_pLeft, expectedSum, path, currentSum);
    if (pRoot->m_pRight != nullptr)
        FindPath(pRoot->m_pRight, expectedSum, path, currentSum);

    //  在返回到父结点之前,在路径上删除当前结点,
    //  并在currentSum中减去当前结点的值
    currentSum -= pRoot->m_nValue;
    path.pop_back();
}

void FindPath(BinaryTreeNode* pRoot, int expectedSum)
{
    if (pRoot == nullptr)
        return;

    std::vector<int> path;
    int currentSum = 0;
    FindPath(pRoot, expectedSum, path, currentSum);
}



int main()
{
    BinaryTreeNode node_1 = {4, nullptr, nullptr};
    BinaryTreeNode node_2 = {7, nullptr, nullptr};
    BinaryTreeNode node_3 = {12, nullptr, nullptr};
    BinaryTreeNode node_4 = {5, &node_1, &node_2};
    BinaryTreeNode root = {10, &node_4, &node_3};

    FindPath(&root,22);

    return EXIT_SUCCESS;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值