五:二叉树中和为某一直的路径

比如:求和为22的路径



求值步骤



规律:当用前序遍历的方式訪问到某一节点时,我们把这个节点加入到路径上,并累加该节点的值,假设该节点为叶子节点而且路径中节点值的和刚好等于输入的整数。则当前的路径符合要求。我们把它打印出来。假设当前节点不是叶节点。则继续訪问它的子节点。

当前节点訪问结束后。递归函数将自己主动回到它的父节点。

因此我们在函数退出之前要在路径上删除当前节点。并减去当前节点的值,以确保返回父节点时路径刚好是从根节点到父节点的路径。不难看出保存路径的数据结构实际上是一个栈,由于路径要与递归调用状态一致,而递归调用的本质就是一个压栈和出栈的过程。

可是因为使用栈不便于路径的输出,所以能够借助于vector的push_back和pop_back在尾部增删路径节点,实现栈的功能。


代码例如以下:

voidFindPath

(

    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 == NULL&& pRoot->m_pRight == NULL;

    if(currentSum == expectedSum &&isLeaf)

    {

        printf("A path is found: ");

       std::vector<int>::iterator iter = path.begin();

        for(; iter != path.end(); ++ iter)

            printf("%d ", *iter);

       

        printf(" ");

    }

 

    //假设不是叶结点。则遍历它的子结点

    if(pRoot->m_pLeft != NULL)

        FindPath(pRoot->m_pLeft,expectedSum, path, currentSum);

    if(pRoot->m_pRight != NULL)

        FindPath(pRoot->m_pRight,expectedSum, path, currentSum);

 

    //在返回到父结点之前。在路径上删除当前结点。

    //并在currentSum中减去当前结点的值

    currentSum -= pRoot->m_nValue;

    path.pop_back();

}

 

voidCallFindPath(BinaryTreeNode* pRoot, int expectedSum)

{

    if(pRoot == NULL)

        return;

 

    std::vector<int> path;

    int currentSum = 0;

    FindPath(pRoot, expectedSum, path,currentSum);

}



原文地址:https://www.cnblogs.com/zfyouxi/p/5389760.html