LeetCode 145. 二叉树的后序遍历

给定一个二叉树,返回它的 后序 遍历。

示例:

输入: [1,null,2,3]
1
\
2
/
3

输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal

迭代:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> postorderTraversal(TreeNode* root) {
13        vector<int> ans;
14         if(!root) return ans;
15         stack<TreeNode*> nodeStack1,nodeStack2;
16         TreeNode* node;
17         nodeStack1.push(root);
18         while( !nodeStack1.empty())
19         {
20             node = nodeStack1.top();
21             nodeStack1.pop();
22             nodeStack2.push(node);
23             if(node->left) 
24                 nodeStack1.push(node->left);
25             if(node->right)
26                 nodeStack1.push(node->right);
27         }
28 
29         while(!nodeStack2.empty())
30         {
31             ans.push_back(nodeStack2.top()->val);
32             nodeStack2.pop();
33         }
34 
35         return ans;
36     }
37 };

 

优化:来源:

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ans;
        if(root == NULL){
            return ans;
        }
        
        stack<TreeNode*> q;
        TreeNode *p = root;
        TreeNode *pLast = NULL;
        while(p){
            q.push(p);
            p = p->left;
        }
        while(!q.empty()){
            p = q.top();
            q.pop();
            // 右无或者右看过,可以看中
            if(!p->right || p->right==pLast){
                ans.push_back(p->val);
                pLast = p;
            }else{
                // 进入右
                q.push(p);
                p = p->right;
                while(p){
                    q.push(p);
                    p = p->left;
                }
            }
        }
        
        return ans;
    }
};

 

posted @ 2019-09-08 17:18  听说这是最长的名字了  阅读(182)  评论(0编辑  收藏  举报