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

本文介绍了一种算法,用于在给定的二元树中找到所有路径,这些路径从树的根节点开始,直到叶节点,并且路径上所有节点的值之和等于指定的整数值。通过递归过程,算法能够识别并输出满足条件的路径。

题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
  10 
  / /  
 5 12  
 /  /  
4     7
则打印出两条路径:10, 1210, 5, 7

二元树节点的数据结构定义为:
struct BinaryTreeNode // a node in the binary tree
{
int m_nValue; // value of node
BinaryTreeNode *m_pLeft; // left child of node
BinaryTreeNode *m_pRight; // right child of node
};


算法:

这是个递归的过程,也就是从10 — 5 — 4, 10—5 —7, 10—12路径中找出等于22的,每次遍历到叶节点,将路径保存在path容器中,如果累加到叶节点的值等于22,当然输出,否则从路径容器中删除这个值,具体的算法

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

struct BinaryTreeNode // a node in the binary tree
{
	int m_nValue; // value of node
	BinaryTreeNode *m_pLeft; // left child of node
	BinaryTreeNode *m_pRight; // right child of node
};

vector<BinaryTreeNode*> pathVec;

void creatTree(BinaryTreeNode *&root, int *a, int i, int len)
{
	if(i >= len)
		return;
	root = new BinaryTreeNode;
	root->m_nValue = a[i];
	root->m_pLeft = NULL;
	root->m_pRight = NULL;
	creatTree(root->m_pLeft, a, 2*i + 1, len);
	creatTree(root->m_pRight, a, 2*i + 2, len);
}

void preorder(BinaryTreeNode* &root)
{
	if(!root)
		return;
	cout << root->m_nValue << " ";
	preorder(root->m_pLeft);
	preorder(root->m_pRight);	
}

void printPath(vector<BinaryTreeNode*>& pathVec)
{
	for(vector<BinaryTreeNode*>::iterator it = pathVec.begin(); it != pathVec.end(); it++)
		cout << (*it)->m_nValue << " ";
	cout << endl;
}

void pathTree(BinaryTreeNode* &root, int val)
{
//输出二叉树中路径等于val的所有路径
	static int sum = 0;
	sum += root->m_nValue;
	pathVec.push_back(root);
	if(sum == val && root->m_pLeft == NULL && root->m_pRight == NULL)
		printPath(pathVec);
	if(root->m_pLeft)
		pathTree(root->m_pLeft, val);
	if(root->m_pRight)
		pathTree(root->m_pRight, val);
	sum -= root->m_nValue;
	pathVec.pop_back();
}

int main()
{
	BinaryTreeNode *root = 0;
	int a[] = {10, 5, 12, 7, 8};
	int len = sizeof a / sizeof a[0];
	creatTree(root, a, 0, len);
//	preorder(root);
	pathTree(root, 22);
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值