欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode 145 二叉树的后序遍历

程序员文章站 2022-05-20 13:45:07
...
//解法一:递归版算法
/**
 * 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> ret;
        
        postorder(root,ret);

        return ret;
    }

    void postorder(TreeNode* root,vector<int>& v)
    {
         if(root!=NULL)
         {
             postorder(root->left,v);
             postorder(root->right,v);
             v.push_back(root->val);
         }
    }
};

 

//非递归算法:
//Time:O(n) Space:O(n)
/**
 * 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> ret;
        stack<TreeNode*> s;
        TreeNode* pre=NULL;

        while(root!=NULL||!s.empty())
        {
            if(root!=NULL)
            {
                s.push(root);
                root=root->left;
            }
            else
            {
                root=s.top();
                root=root->right;

                if(root==NULL||root==pre)
                {
                    pre=s.top();
                    s.pop();
                    ret.push_back(pre->val);
                    root=NULL;
                }
            }
        }

        return ret;
    }
};