【转】在二元树中找出和为某一值的所有路径

来源:互联网 发布:学好高中数学的软件 编辑:程序博客网 时间:2024/06/06 07:48


二叉树中叶子结点到根的最长路径和最短路径

[cpp] view plaincopyprint?
  1. void preorder( Node* pNode, vector<Node*>& path, vector<Node*>& longest, vector<Node*>& shortest ) {  
  2.     if( pNode == 0 ) {  
  3.         if( longest.size() < path.size() ) {  
  4.             longest = path;  
  5.         } else if( shortest.size() == 0 || shortest.size() > path.size() ) {  
  6.             shortest = path;  
  7.         }  
  8.     } else {  
  9.         path.push_back( pNode );  
  10.         postorder( pNode->left, path, longest, shortest );  
  11.         postorder( pNode->right, path, longest, shortest );  
  12.         path.pop_back();  
  13.     }  
  14. }  
  15.   
  16. void printPath( vector<Node*>& path ) {  
  17.     forint i = 0, n = path.size(); i < n; i++ ) {  
  18.         printf( "%d ", path[i]->data );  
  19.     }  
  20.     printf( "\n" );  
  21. }  
  22.   
  23. void test( Node* root ) {  
  24.     vector<Node*> path;  
  25.     vector<Node*> longest;  
  26.     vector<Node*> shortest;  
  27.   
  28.     postorder( root, path, longest, shortest );  
  29.   
  30.     printf("longest:" );  
  31.     printPath( longest );  
  32.     printf( "shortest:" );  
  33.     printPath( shortest );  
  34. }