在二元树中找出和为某一值的所有路径

输入一个整数和一棵二元树,从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径,然后打印出和与输入整数相等的所有路径。

#include <iostream>
#include<stack>
#include<vector>
using namespace std;

typedef struct BinaryTreeNode {
	int m_nValue;
	BinaryTreeNode * m_pLeft;
	BinaryTreeNode * m_pRight;
} BinaryTreeNode; /* 表示一个元素的三元组结构 */

vector<int> vec;

void initTree(BinaryTreeNode* head);
void findRoute(BinaryTreeNode* head, int arg0, int count);

int main() {
	BinaryTreeNode* head = new BinaryTreeNode();
	initTree(head);

	int arg0 = 22;

	int count = 0;
	cout << "二叉树中和为" << arg0 << "的路径:" << endl;
	findRoute(head, arg0, count);

	return 0;
}

void initTree(BinaryTreeNode* head) {
	if (!head)
		return;

	BinaryTreeNode* child1 = new BinaryTreeNode();
	BinaryTreeNode* child2 = new BinaryTreeNode();
	BinaryTreeNode* child3 = new BinaryTreeNode();
	BinaryTreeNode* child4 = new BinaryTreeNode();

	head->m_nValue = 10;
	child1->m_nValue = 5;
	child2->m_nValue = 12;
	child3->m_nValue = 4;
	child4->m_nValue = 7;

	head->m_pLeft = child1;
	head->m_pRight = child2;

	child1->m_pLeft = child3;
	child1->m_pRight = child4;

}

void findRoute(BinaryTreeNode* head, int arg0, int count) {
	if (!head) {
		return;
	} else {
		if (count + head->m_nValue == arg0) {
			if (head->m_pLeft || head->m_pRight) {	//非叶子结点
				return;
			} else {
				for (int i = 0; i < vec.size(); ++i) {
					cout << " " << vec[i];
				}
				cout << " " << head->m_nValue << endl;
				return;
			}
		} else if (count + head->m_nValue > arg0) {
			return;
		} else {
			if (head->m_pLeft) {
				vec.push_back(head->m_nValue);
				findRoute(head->m_pLeft, arg0, count + head->m_nValue);
				vec.erase(vec.end() - 1);
			}
			if (head->m_pRight) {
				vec.push_back(head->m_nValue);
				findRoute(head->m_pRight, arg0, count + head->m_nValue);
				vec.erase(vec.end() - 1);
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值