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

来源:互联网 发布:海绵宝宝 知乎 编辑:程序博客网 时间:2024/06/05 04:17

【题目】

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

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

以下图中二叉树为例

这里写图片描述


【分析】

从数的根结点开始往下一直到叶结点所经过的结点形成一条路径,在二叉树遍历方法中只有前序遍历从根节点开始,所以按照前序遍历访问时,访问顺序为10,5,4,7,12,而观察二叉树所有路径中,等于22的有两条路径:{10,5,7}和{10,12},访问过程如下:
1. 访问根结点10,添加到路径path中,记录下此时路径和为10;
2. 按照前序遍历依次访问,访问5,添加到路径path中,路径和为15;
3. 访问4为叶子结点,添加到路径path中,路径和为19不等于22,故从路径path中删除结点4,返回结点5,访问父节点5的右孩子7,添加到路径path中,路径和就为15+7 =22,将路径path中数据依次输出,路径10-5-7;
4. 删除路径中记录的结点数据,留下结点10,访问其右孩子12,添加到路径path中,路径和为22,输出路径10-12;

由上分析可以发现,路径path的功能类似于栈,递归调用本身就是一个栈的实现过程。


【测试代码】

#include<iostream>#include<vector>using namespace std;struct BinaryTreeNode{    int                 m_nValue;    BinaryTreeNode*     m_pLeft;    BinaryTreeNode*     m_pRight;};BinaryTreeNode* createBinaryTreeNode(int value){    BinaryTreeNode* pNode = new BinaryTreeNode();    pNode->m_nValue = value;    pNode->m_pLeft = NULL;    pNode->m_pRight = NULL;    return pNode;}void connectBinaryTreeNode(BinaryTreeNode* pParent, BinaryTreeNode* pLeftChild,                           BinaryTreeNode* pRightChild){    if(!pParent || !pLeftChild || !pRightChild)        return;    pParent->m_pLeft = pLeftChild;    pParent->m_pRight = pRightChild;}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(currentSum == expectedSum && isLeaf)    {        printf(" path is found: ");        vector<int >::iterator iter = path.begin( );        for( ; iter != path.end() ; ++iter)            printf("%d\t", *iter);        printf("\n");    }    //如果不是叶结点,则遍历它的子结点    if( pRoot->m_pLeft != NULL)        FindPath(pRoot->m_pLeft,  expectedSum, path, currentSum);    if( pRoot->m_pRight != NULL)        FindPath(pRoot->m_pRight,  expectedSum, path, currentSum);    //在返回到父结点之前,在路径上删除当前结点    path.pop_back( );}void FindTreePath(BinaryTreeNode* pRoot, int expectedSum){    if(pRoot == NULL)        return ;    vector<int> path;    int currentSum = 0 ;    FindPath(pRoot, expectedSum, path, currentSum);}void test(){    BinaryTreeNode* pNode1 = createBinaryTreeNode(10);    BinaryTreeNode* pNode2 = createBinaryTreeNode(5);    BinaryTreeNode* pNode3 = createBinaryTreeNode(12);    BinaryTreeNode* pNode4 = createBinaryTreeNode(4);    BinaryTreeNode* pNode5 = createBinaryTreeNode(7);    connectBinaryTreeNode(pNode1,pNode2,pNode3);    connectBinaryTreeNode(pNode2,pNode4,pNode5);    int expectedSum =22;    FindTreePath( pNode1, expectedSum);}int main(){    test();    system("pause");    return 0;}

【输出】

这里写图片描述

0 0