二叉树中和为某一值的路径
2015-08-24 22:23
330 查看
题目:
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径.从树的根结点开始往下一直到叶结点所经过的结点形成一条路径.
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径.从树的根结点开始往下一直到叶结点所经过的结点形成一条路径.
[code]#include <vector> #include <stdio.h> using std::vector; void FindPath(BinaryTreeNode* pRoot, int expectedSum, vector<int>& path, int currentSum); void FindPath(BinaryTreeNode* pRoot, int expectedSum) { if (pRoot == NULL) return; vector<int> path; int currentSum = 0; FindPath(pRoot, expectedSum, path, currentSum); } 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 (isLeaf && currentSum == expectedSum) { vector<int>::iterator iter = path.begin(); for (; iter != path.end(); ++iter) { printf("%d ",*iter); } printf("\n"); } if (pRoot->m_pLeft) FindPath(pRoot->m_pLeft, expectedSum, path, currentSum); if (pRoot->m_pRight) FindPath(pRoot->m_pRight, expectedSum, path, currentSum); //返回父结点前,在路径上删除当前结点 path.pop_back(); }
相关文章推荐
- android L 启动流程
- Xcode各版本和IOS模拟器个版本下载
- 字符串合并处理 (中级)
- Java之旅hibernate(8)——基本关系映射
- 1.主动学习很重要,主动学习很重要,主动学习很重要 2.官方文档 3.实践(转)
- uva1379
- Intel Threading Building Blocks (TBB入门)
- 数组中存放0到n中的缺少一个数的连续数,找出该缺少的数
- [sharepoint]修改Item或者File的Author和Editor
- 分析函数优化自关联2
- Per相关图书推荐
- hdu1213
- 第五 JDBC技术
- ios swift圆形按钮和圆形图标
- spring boot demo( 获取一个RESTful web service)
- MATLAB相关图书推荐
- .Net分布式异常报警系统-简介
- csharp: SDK:CAPICOM
- SQLPLUS使用技巧
- listview异步加载图片并防止错位