二叉树遍历

二叉树前序遍历,中序遍历,后序遍历。

 1 void preOrder_N(BTNode* root)
 2 {
 3     stack<BTNode*> s;
 4     while(root!=NULL||!s.empty())
 5     {
 6         if(root!=NULL)
 7         {
 8             cout<<root->data<<"-->";
 9             s.push(root);
10             root=root->left;
11         }
12         else
13         {
14             root=s.top();
15             s.pop();
16             root=root->right;
17         }
18     }
19 }
20 void inOrder_N(BTNode* root)
21 {
22     stack<BTNode*> s;
23     while(root!=NULL||!s.empty())
24     {
25         if(root!=NULL)
26         {
27             s.push(root);
28             root=root->left;
29         }
30         else
31         {
32             root=s.top();
33             s.pop();
34             cout<<root->data<<"-->";
35             root=root->right;
36         }
37     }
38 }
39 void postOrder_N(BTNode* root)
40 {
41     stack<BTNode*> s;
    /*
    *记录前一个访问的节点。在后序遍历中,p节点总是在p节点的rightchild之后输出。所以记录前一个输出的节点和P节点的有孩子比较。一致则右孩子访问过了。
    *需要访问p节点并将其弹出。
    */
42 BTNode* pre=NULL; 43 while(root!=NULL||!s.empty()) 44 { 45 while(root!=NULL) 46 { 47 s.push(root); 48 root=root->left; 49 } 50 root=s.top(); 51 if(root->right==NULL||root->right==pre) 52 { 53 cout<<root->data<<"->"; 54 s.pop(); 55 pre=root; 56 root=NULL;//!!!important 57 58 }else 59 { 60 root=root->right; 61 62 } 63 } 64 }

 

posted @ 2014-07-06 09:39  Hicandyman  阅读(147)  评论(0)    收藏  举报