二叉树中和为某一值的路径(剑指offer25)

题目:输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所以路径。从树的根结点开始往下一直到叶子结点所经过的结点形成一条路径。

二叉树的结点结构

struct BinaryTreeNode {
	int m_nValue; //用于结点是整数数值的情况
	BinaryTreeNode* m_pLeftChild;
	BinaryTreeNode* m_pRightChild;
};
//二叉树中和为某一值的路径
void findPath(BinaryTreeNode* pRootNode, int expectedSum) {
	if (NULL == pRootNode) {
		return;
	}

	std::vector<int> path;
	int currentSum = 0;
	findPathSum(pRootNode, expectedSum, path, currentSum);
}
void findPathSum(BinaryTreeNode* pRootNode, int expectedSum,
		std::vector<int> &path, int currentSum) {

	currentSum = currentSum + pRootNode->m_nValue;
	path.push_back(pRootNode->m_nValue);

	//判断当前结点是否是叶子结点
	bool isLeafNode = NULL == pRootNode->m_pLeftChild
			&& NULL == pRootNode->m_pRightChild;
	if (currentSum == expectedSum && isLeafNode) {
		cout << "一条路径是:" << endl;
		std::vector<int>::iterator iter = path.begin();
		for (; iter != path.end(); ++iter) {
			cout << *iter << '\t';
		}
		cout << endl;
	}

	if (NULL != pRootNode->m_pLeftChild) {
		findPathSum(pRootNode->m_pLeftChild, expectedSum, path, currentSum);
	}

	if (NULL != pRootNode->m_pRightChild) {
		findPathSum(pRootNode->m_pRightChild, expectedSum, path, currentSum);
	}

	path.pop_back();
}

测试代码

/*
 *
 *  Created on: 2014-4-26 22:13:11
 *      Author: danDingCongRong
 */

#include <stddef.h>
#include <iostream>
#include <vector>

using namespace std;

int main() {
	int sum = 0, count = 0;
	cout << "输入数据的组数:" << endl;
	cin >> count;
	for (int i = 1; i <= count; ++i) {
		cout << "输入第" << i << "组路径和及数据:" << endl;
		cin >> sum;

		BinaryTreeNode * BTNode = NULL;
		BTNode = createIntBinaryTree();
		cout << "二叉树的前序遍历(非递归):" << endl;
		preorderTravesal_loop(BTNode);
		cout << endl;

		findPath(BTNode, sum);
	}

	return 0;
}

注:部分内容参考自剑指offer

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值