树的非递归遍历——前序、中序、后序

树的递归遍历非常简单,也是写树的遍历时最常用的写法。但是我发现自己对树的非递归遍历并不十分熟悉,所以把三种非递归遍历都写了一遍,以后看到这篇记录博客也可以帮助自己好好回想熟悉一下。

Leetcode对应习题:前序中序后序

相对而言,这三种非递归遍历的难度——前序 < 中序 < 后序。

对于第三种(非递归后序遍历)方法,只要稍微调整下第18~19行三个节点push的顺序,就可以实现前中后序的遍历。

树的非递归前序:

 1 class Solution {
 2 public:
 3     vector<int> preorderTraversal(TreeNode* root) {
 4         vector<int> re;
 5         stack<TreeNode*> s;
 6         s.push(root);
 7         while(!s.empty()){
 8             TreeNode *temp = s.top();
 9             s.pop();
10             if(!temp) continue;
11             re.push_back(temp->val);
12             s.push(temp->right);
13             s.push(temp->left);
14         }
15         return re;
16     }
17 };

树的非递归中序:

 1 class Solution {
 2 public:
 3     vector<int> inorderTraversal(TreeNode* root) {
 4         stack<TreeNode*> s;
 5         vector<int> re;
 6         TreeNode *t = root;
 7         while(!s.empty() || t){
 8             while(t){
 9                 s.push(t);
10                 t = t -> left;
11             }
12             if(!s.empty()){
13                 TreeNode *temp = s.top();
14                 s.pop();
15                 re.push_back(temp->val);
16                 t = temp->right;
17             }
18         }
19         return re;
20     }
21 };

 

树的非递归后序遍历:

 1 class Solution {
 2 public:
 3     vector<int> postorderTraversal(TreeNode* root) {
 4         stack<pair<TreeNode*, bool> > s;
 5         vector<int> re;
 6         s.push(make_pair(root, false));
 7         bool visited;
 8         while(!s.empty()){
 9             pair<TreeNode*, bool> p = s.top();
10             s.pop();
11             visited = p.second;
12             if(!p.first){
13                 continue;
14             }
15             if(visited){
16                 re.push_back(p.first->val);
17             }else{
18                 s.push(make_pair(p.first, true));
19                 s.push(make_pair(p.first->right, false));
20                 s.push(make_pair(p.first->left, false));
21             }
22         }
23         return re;
24     }
25 };

 

posted @ 2018-09-11 22:56  liangf27  阅读(1094)  评论(0编辑  收藏  举报