LeetCode145. 二叉树的后序遍历(Binary tree Postorder Traversal)

版权声明:转载请说明出处!!! https://blog.csdn.net/u012585868/article/details/83989724

题目描述

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

示例:

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

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

解题思路1:
用两个栈和一个数组。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        stack<TreeNode*> s1;
        stack<TreeNode*> s2;
        vector<int> res;
        if(!root){
            return res;
        }
        s1.push(root);
        TreeNode* p=root;
        while(!s1.empty()){
            p=s1.top();
            s1.pop();
            s2.push(p);
            if(p->left!=NULL){
                s1.push(p->left);
            }
            if(p->right!=NULL){
                s1.push(p->right);
            }
        }
        while(!s2.empty()){
            p=s2.top();
            res.push_back(p->val);
            s2.pop();
        }
        return res;
    }
};

解题思路2:
用一个栈和一个数组。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        stack<TreeNode*> s;
        TreeNode* p=root,* last_visit=root;
        vector<int> res;
        while(p!=NULL||!s.empty()){
            while(p!=NULL){
                s.push(p);
                p=p->left;
            }
            p=s.top();
            if(p->right==NULL||last_visit==p->right){
                res.push_back(p->val);
                last_visit=p;
                s.pop();
                p=NULL;
            }
            else{
                p=p->right;
            }
        }
        return res;
    }
};

递归:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> out;
        postorder(root, out);
        return out;
    }
    void postorder(TreeNode* root, vector<int>& out) {
        if(root == NULL)
            return;
        postorder(root->left, out);
        postorder(root->right, out);
        out.push_back(root -> val);
    }
};

猜你喜欢

转载自blog.csdn.net/u012585868/article/details/83989724
今日推荐