题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数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
};
这里在程序中采用一个数组来记录数中节点的值,该数组的长度所存储的最大长度为树的高度。这里在每次递归的时候,记录当前节点在树中的位置和值,所以每次递归到叶子节点时,数组中存储的是当前路径的元素。然后把个元素相加,判断值是不是与给定的值相等。相等则打印。
#include <iostream>
using namespace std;
const int max_size = 30 ;
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
BSTreeNode();
BSTreeNode(int value);
};
void getpath(BSTreeNode** root,int n,int arr[],int d);//遍历得到每一条路径
void insert(BSTreeNode** root,int n); //出入元素
void dataprint(int arr[],int n); //打印元素
bool sum(int* arr,int n,int d); //计算和
int main()
{
int n = 0 ;
int data[max_size];
int d = 25 ; //目的数之和
BSTreeNode* root = NULL;
BSTreeNode* temp = NULL;
insert(&root,10);
insert(&root,6);
insert(&root,15);
insert(&root,4);
insert(&root,9);
insert(&root,5);
getpath(&root,n,data,d);
system("pause");
return 0;
}
void getpath(BSTreeNode** root,int n,int arr[],int d)
{
int temp ;
if ((*root) != NULL)
{
temp = n;
arr[temp] = (*root)->m_nValue ;
if ((*root)->m_pLeft == NULL && (*root)->m_pRight == NULL)
{
if (sum(arr,temp,d))
dataprint(arr,temp);
}
getpath(&((*root)->m_pLeft),temp+1,arr,d);
getpath(&((*root)->m_pRight),temp+1,arr,d);
}
}
void insert(BSTreeNode** root,int n)
{
BSTreeNode* temp = new BSTreeNode;
BSTreeNode* current ;
temp->m_nValue = n ;
temp->m_pLeft = NULL ;
temp->m_pRight = NULL ;
if (*root == NULL)
{
*root = new BSTreeNode(n);
}
else
{
current = *root ;
while(current != NULL)
{
if (current->m_nValue>n&¤t->m_pLeft==NULL)
{
current->m_pLeft = temp ;
break;
}
else if (current->m_nValue>n&¤t->m_pLeft!=NULL)
{
current = current->m_pLeft;
continue;
}
else if (current->m_nValue<n&¤t->m_pRight==NULL)
{
current->m_pRight = temp;
break;
}
else if (current->m_nValue<n&¤t->m_pRight!=NULL)
{
current = current->m_pRight;
continue;
}
}
}
}
BSTreeNode::BSTreeNode(int value)
{
m_nValue = value ;
m_pLeft = NULL ;
m_pRight = NULL ;
}
BSTreeNode::BSTreeNode()
{}
void dataprint(int arr[],int n)
{
for (int i=0;i<=n;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
bool sum(int* arr,int n,int d)
{
int sumtemp = 0 ;
for (int i=0;i<n+1;i++)
sumtemp = sumtemp + arr[i];
if (sumtemp == d)
return true;
else return false;
}