码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的前序、中序、后序

时间:2020-03-23 16:49:34      阅读:47      评论:0      收藏:0      [点我收藏+]

标签:head   list   class   tac   out   stack   ack   后序   二叉树   

 1 //前序
 2 void preOrderUnRecur(ListNode* head)
 3 {
 4     cout << "pre-order: ";
 5     if (head != NULL)
 6     {
 7         stack<ListNode*> Stack;
 8         Stack.push(head);
 9 
10         while (!Stack.empty())
11         {
12             head = Stack.top();
13             Stack.pop();
14             cout << head->value << " ";
15             if (head->right != NULL)
16             {
17                 Stack.push(head->right);
18             }
19             if (head->left != NULL)
20             {
21                 Stack.push(head->left);
22             }
23         }
24     }
25 }
26 
27 //中序
28 void inOrderUnRecur(ListNode* head)
29 {
30     cout << "in-order: ";
31     if (head != NULL)
32     {
33         stack<ListNode*> Stack;
34         while (!Stack.empty() || head != NULL)
35         {
36             if (head != NULL)
37             {
38                 Stack.push(head);
39                 head = head->left;
40             }
41             else
42             {
43                 head = Stack.top();
44                 Stack.pop();
45                 cout << head->value << " ";
46                 head = head->right;
47             }
48         }
49     }
50 }
51 
52 //后序
53 void posOrderUnRecur(ListNode* head)
54 {
55     cout << "pos-order: ";
56     if (head != NULL)
57     {
58         stack<ListNode*> s1;
59         stack<ListNode*> s2;
60         s1.push(head);
61         while (!s1.empty())
62         {
63             head = s1.top();
64             s1.pop();
65             s2.push(head);
66             if (head->left != NULL)
67             {
68                 s1.push(head->left);
69             }
70             if (head->right != NULL)
71             {
72                 s1.push(head->right);
73             }
74         }
75         while (!s2.empty())
76         {
77             cout << s2.top()->value << " ";
78             s2.pop();
79         }
80     }
81 }

 

二叉树的前序、中序、后序

标签:head   list   class   tac   out   stack   ack   后序   二叉树   

原文地址:https://www.cnblogs.com/yuhong1103/p/12552835.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!