#include <iostream>
typedef 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
}BTNode;
void dfs(int sum ,BTNode *node ,int pace[] , int paceNumber)
{
if( sum == node->m_nValue ){
for (int i = 0; i < paceNumber ; i++ )
std::cout<<pace[i]<<" ";
std::cout<<node->m_nValue;
std::cout<<std::endl;
}
else {
pace[paceNumber] = node->m_nValue ;
if (node->m_pLeft)
dfs( sum - node->m_nValue, node->m_pLeft , pace, paceNumber + 1 ) ;
if (node->m_pRight)
dfs( sum - node->m_nValue, node->m_pRight , pace, paceNumber + 1 ) ;
}
}
BTNode * findPlace(BTNode * root , int key)
{
BTNode * temp = root ;
BTNode * pparent = root ;
while ( temp ) {
if ( temp->m_nValue > key) {
pparent = temp ;
temp = temp->m_pLeft ;
}
else {
pparent = temp ;
temp = temp->m_pRight ;
}
}
return pparent ;
}
BTNode * buildTree(int length, int a[])
{
BTNode *root = NULL ;
BTNode *temp = NULL ;
BTNode *addNode = NULL ;
int i = 0 ;
root = temp = (BTNode *) malloc(sizeof(BTNode) ) ;
temp->m_nValue = a[0] ;
temp->m_pLeft = temp->m_pRight = NULL ;
for ( i = 1 ; i < length ; i++)
{
temp = findPlace(root, a[i]);
addNode = (BTNode *) malloc(sizeof(BTNode)) ;
addNode->m_pLeft = addNode->m_pRight = NULL ;
addNode->m_nValue = a[i] ;
if ( temp->m_nValue > a[i] ) {
temp->m_pLeft = addNode ;
}
else {
temp->m_pRight = addNode ;
}
}
return root ;
}
int main()
{
int a[] ={10,5,4,7,12};
BTNode *root = buildTree(5, a);
int p[4];
dfs(22, root, p, 0);
return 0;
}
深度优先遍历数可得结果