微軟等數據結構+算法面試100題004

#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;

}

 

 

深度優先遍歷數可得結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章