数据结构练习(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(); }
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------