您的位置:首页 > 其它

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

2012-03-20 21:02 211 查看
题目:输入一个整数和一棵二元树。

从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。

打印出和与输入整数相等的所有路径。

例如 输入整数22和如下二元树

10

/ /

5 12

/ /

4 7

则打印出两条路径:10, 12和10, 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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: