题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数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);
}
本文介绍了一种算法,用于在给定的二元树中找到所有路径,这些路径从树的根节点开始,直到叶节点,并且路径上所有节点的值之和等于指定的整数值。通过递归过程,算法能够识别并输出满足条件的路径。
4515

被折叠的 条评论
为什么被折叠?



