二叉树中和为某一值的路径
2015-07-08 22:21
190 查看
、
void FindPath(BinaryTreeNode* pRoot, int expectedSum)
{
if (pRoot == NULL)
return;
std::vector<int> path;
int currentSum = 0;
FindPath(pRoot, expectedSum, path, currentSum);
}
void FindPath(BinaryTreeNode* pRoot, int expectedSum, std::vector<int>& path, int& currentSum)
{
currentSum += pRoot->m_nValue;
path.push_back(pRoot->m_nValue);
//如果是叶结点,并且路径上结点的和等于输入的值
//打印输出这条路径
bool isLeaf = pRoot->m_pLefat == 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\t", *iter);
printf("\n");
}
//如果不是叶节点,则遍历它的子结点
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();
}
相关文章推荐
- 《Spring3.0就这么简单》第1章快速入门
- Linux系统NFS故障现象
- Oracle ORA-28001: the password has expired
- 24.二叉搜索树的后序遍历序列
- C++实现中序线索二叉树
- Next Permutation
- InvocationHandler
- lsof命令列出当前系统打开文件
- 退出响应
- 观察者模式
- iOS 圆角矩形圆角设置
- win7下在安装Oracle10g时出现【安装检测到系统的主 IP 地址是 DHCP 分配的地址】的错误的解决办法
- 遇見那個eclipse
- imx6 驱动文件目录
- BZOJ 1305: [CQOI2009]dance跳舞( 最大流 )
- 云服务器:西部数码VS阿里云
- JdkDynamicAopProxy源码
- 利用tkprof查看trace文件
- karloop介绍--hello world大家好,今天为大家介绍一款非常轻量级的的web开发框架,karloop框架。使用python开发 首先我们下载karloop源码进行安装。 源码地址 下载成
- Gym 100548A Built with Qinghuai and Ari Factor (Asia Xian)