剑指Offer第25题(二叉树中和为某一值的路径)

(本博客旨在个人总结回顾)

题目描述:

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

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

        例如输入如图4.7 中二叉树和整数22,则打印出两条路径,一条路径包含结点10、12,第二条路径包含结点10、5和7。

完整代码:

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

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


/*
* @name   PrintPathSumOfNTree
* @brief  打印二叉树中和为某一值的路径(递归)
* @param  [in] BinaryTreeNode * pNode  当前路径遍历的结点
* @param  [in] vector<int>vecPath      当前遍历前的路径
* @param  [in] int nCurSum             当前遍历结点和
* @param  [in] int nSum                完整路径和
* @return void
*/
void PrintPathSumOfNTree(BinaryTreeNode* pNode, vector<int>& vecPath, int nCurSum, int nSum)
{
    if (NULL == pNode)
    {
        return;
    }
    nCurSum = nCurSum + pNode->m_nValue;
    if (nCurSum > nSum)
    {
        return;
    }
    vecPath.push_back(pNode->m_nValue);
    if (NULL == pNode->m_pLeft && NULL == pNode->m_pRight && nCurSum == nSum)
    {
        for (vector<int>::iterator it = vecPath.begin(); it != vecPath.end(); it++)
        {
            cout << *it << " ";
        }
        cout << endl;

    }
    if (NULL != pNode->m_pLeft)
    {
        PrintPathSumOfNTree(pNode->m_pLeft, vecPath, nCurSum, nSum);
    }
    if (NULL != pNode->m_pRight)
    {
        PrintPathSumOfNTree(pNode->m_pRight, vecPath, nCurSum, nSum);
    }
    vecPath.pop_back();
}

int _tmain(int argc, _TCHAR* argv[])
{
    BinaryTreeNode* pRoot = new BinaryTreeNode();
    pRoot->m_nValue = 10;

    BinaryTreeNode* pTmp = new BinaryTreeNode();
    pTmp->m_nValue = 5;
    pRoot->m_pLeft = pTmp;

    pTmp = new BinaryTreeNode();
    pTmp->m_nValue = 4;
    pRoot->m_pLeft->m_pLeft = pTmp;

    pTmp = new BinaryTreeNode();
    pTmp->m_nValue = 7;
    pRoot->m_pLeft->m_pRight = pTmp;

    pTmp = new BinaryTreeNode();
    pTmp->m_nValue = 12;
    pRoot->m_pRight = pTmp;

    vector<int> vecPath;
    PrintPathSumOfNTree(pRoot, vecPath, 0, 22);
    system("pause");
    return 0;
}

运行结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值