数据结构练习(03)二元树中和为某一值的所有路径

http://zhedahht.blog.163.com/blog/static/254111742007228357325/

思路:

很简单的递归了。

struct tree {
    int m_value;
    tree *m_left;
    tree *m_right;
};

int sum;

void findpath(tree *root, std::vector<int>& path, int& cursum)
{
    if (!root)
        return;

    cursum += root->m_value;
    path.push_back(root->m_value);

    bool isleaf = (!root->m_left && !root->m_right);

    if (cursum == sum && isleaf)
    {
        std::vector<int>::iterator v = path.begin();
        for (; v != path.end(); ++v)
            std::cout << *v << ' ';
        std::cout << std::endl;
    }

    if (root->m_left)
        findpath(root->m_left, path, cursum);
    if (root->m_right)
        findpath(root->m_right, path, cursum);

    cursum -= root->m_value;
    path.pop_back();
}

 

posted @ 2012-12-11 15:41  kedebug  阅读(225)  评论(0编辑  收藏  举报