深度优先的C++ 实现

 

  1. #include <iostream> 
  2. #include <stack> 
  3. using namespace std; 
  4.  
  5. struct node  
  6.     int self; //数据  
  7.     node *left; //左节点  
  8.     node *right; //右节点  
  9.  }; 
  10.  
  11. void main() 
  12.  
  13.      
  14.     const int TREE_SIZE = 9; 
  15.     std::stack <node*> visited, unvisited; 
  16.     node nodes[TREE_SIZE];  
  17.     node* current; 
  18.     forint i=0; i<TREE_SIZE; i++) //初始化树 
  19.     { 
  20.         nodes[i].self = i; 
  21.         int child = i*2+1; 
  22.         if( child<TREE_SIZE ) //Left child 
  23.             nodes[i].left = &nodes[child]; 
  24.         else 
  25.             nodes[i].left = NULL; 
  26.         child++; 
  27.         if( child<TREE_SIZE ) //Right child     
  28.             nodes[i].right = &nodes[child]; 
  29.         else 
  30.             nodes[i].right = NULL; 
  31.     }            
  32.      
  33.     unvisited.push(&nodes[0]); //先把0放入UNVISITED stack 
  34.      
  35.     while(!unvisited.empty()) //只有UNVISITED不空 
  36.          
  37.     { 
  38.         current=(unvisited.top()); //当前应该访问的 
  39.         unvisited.pop();  
  40.          
  41.         if(current->right!=NULL)  
  42.             unvisited.push(current->right); // 把右边压入 因为右边的访问次序是在左边之后 
  43.          
  44.         if(current->left!=NULL)  
  45.             unvisited.push(current->left); 
  46.          
  47.         visited.push(current); 
  48.          
  49.         cout<<current->self<<endl; 
  50.          
  51.  }