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

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

采用前序遍历所有路径。

struct BinaryTreeNode
{
    int value;
    BinaryTreeNode* p_left;
    BinaryTreeNode* p_right;
};

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

    //如果是叶子节点,并且路径上的节点和等于输入的值则打印出这条路径
    bool isleaf = pRoot->p_left== NULL && pRoot->p_right == NULL ;
    if( currentSum == expectedSum && isleaf )
    {
        cout<< "find a path:"<<endl;
        std::vector<int>::iterator iter= path.begin();
        for(;iter != path.end(); ++iter)
            cout<< *iter<<'\t';
        cout<<endl;
    }

    if( pRoot->p_left != NULL)
        FindPath(pRoot->p_left,expectedSum,path,currentSum);
    if(pRoot->p_right != NULL)
        FindPath(pRoot->p_right,expectedSum,path,currentSum);

    //返回到父节点之前,在路径上删除当前节点
    path.pop_back();
}

void FindPath(BinaryTreeNode* pRoot, int expectedSum)
{
    if( pRoot == NULL)
        return;
    std::vector<int > path;
    int currentSum = 0;
    FindPath(pRoot,expectedSum,path,currentSum);
}

 

posted @ 2013-03-06 14:01  没离开过  阅读(119)  评论(0)    收藏  举报