问题
给定一棵二叉树,其中每个结点都含有一个数值。设计一个算法,打印结点数值总和等于某个给定值的所有路径。注意:路径不一定非得从二叉树的根结点或叶节点开始或结束。
思路
采用二次遍历的方式。
1. 在函数func1中,先从根结点开始遍历二叉树,到达当前结点current。
2. 将current传入func2中,遍历current子树,打印二叉树中数值总和等于给定值的路径。
两种实现方式
递归和迭代
这里对子树和二叉树采用相同的遍历方式,并分别采用递归和迭代两种方式来实现遍历。当然,也可以对子树采用与原二叉树不同的遍历方式,即交叉使用递归和迭代方式。
递归实现代码
/********************************************
* Author : Dong Huaan
* Email : donghuaan@163.com
* Filename : PathMatchPathInBinaryTree.cpp
* Creation time : 2018-01-04 18:01:36
* Last modified : 2018-01-04 20:50:37
* Description : ---
*******************************************/
// TOC: rand situation: O(nlog(n))
// SOC: rand situation: O(log(n))
#include<iostream>
#include<list>
#include"BinaryTree.h"
// 打印链表
void printList(const std::list<int> &path)
{
if(!path.empty())
{
for(std::list<int>::const_iterator iter = path.begin(); iter != path.end(); ++iter)
std::cout << *iter << " ";
std::cout << "\n