您的位置:首页 > 其它

二叉树中和为某一值的路径

2015-08-24 22:23 330 查看
题目:

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

[code]#include <vector>
#include <stdio.h>
using std::vector;
void FindPath(BinaryTreeNode* pRoot, int expectedSum, vector<int>& path,
              int currentSum);
void FindPath(BinaryTreeNode* pRoot, int expectedSum)
{
    if (pRoot == NULL)
        return;
    vector<int> path;
    int currentSum = 0;
    FindPath(pRoot, expectedSum, path, currentSum);
}

void FindPath(BinaryTreeNode* pRoot, int expectedSum, vector<int>& path,
              int currentSum)
{
    currentSum += pRoot->m_nValue;
    path.push_back(pRoot->m_nValue);
    bool isLeaf = (pRoot->m_pLeft == NULL && pRoot->m_pRight == NULL);
    //如果是叶子结点并且当前和值和传入整数相等,则打印路径
    if (isLeaf && currentSum == expectedSum)
    {
        vector<int>::iterator iter = path.begin();
        for (; iter != path.end(); ++iter)
        {
            printf("%d ",*iter);
        }
        printf("\n");
    }

    if (pRoot->m_pLeft)
        FindPath(pRoot->m_pLeft, expectedSum, path, currentSum);
    if (pRoot->m_pRight)
        FindPath(pRoot->m_pRight, expectedSum, path, currentSum);
  //返回父结点前,在路径上删除当前结点
    path.pop_back();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: