p34 二叉树的后续遍历 (leetcode 145)

一:解题思路

这道题目有2种方法,第一种是递归法,第二种是迭代法。2种方法的时间和空间复杂度都为O(n)。

二:完整代码示例 (C++版和Java版)

递归C++:

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

    vector<int> postorderTraversal(TreeNode* root) 
    {
        vector<int> ret;

        postorder(root,ret);

        return ret;
    }
};

递归Java:

class Solution {
    public void postorder(TreeNode root,List<Integer> ret)
    {
        if(root!=null)
        {
            postorder(root.left,ret);
            postorder(root.right,ret);
            ret.add(root.val);
        }
    }
    
    public List<Integer> postorderTraversal(TreeNode root) 
    {
           List<Integer> ret=new ArrayList<>();

           postorder(root,ret);
           
           return ret;
    }
}

迭代C++:

class Solution 
{
public:
    vector<int> postorderTraversal(TreeNode* root) 
    {
        vector<int> ret;
        stack<TreeNode*> stack;
        list<int> list;

        if (root != NULL)
            stack.push(root);
        
        while (!stack.empty())
        {
            TreeNode* s = stack.top();
            stack.pop();

            list.push_front(s->val);

            if (s->left != NULL)  stack.push(s->left);
            if (s->right != NULL) stack.push(s->right);
        }

        while (!list.empty())
        {
            ret.push_back(list.front());
            list.pop_front();
        }

        return ret;
    }
};

迭代Java:

class Solution {
    public List<Integer> postorderTraversal(TreeNode root)
    {
           LinkedList<Integer> ret=new LinkedList<>();
           Stack<TreeNode> stack=new Stack<>();
           
           if(root!=null)
               stack.push(root);
           
           while(!stack.isEmpty())
           {
               TreeNode s=stack.pop();
               ret.addFirst(s.val);
               
               if(s.left!=null)  stack.push(s.left);
               if(s.right!=null) stack.push(s.right);
           }
           
           return ret;
    }
}

 

上一篇:二叉树--后序遍历


下一篇:Leetcode练习:从中序与后序遍历序列构造二叉树,递归与迭代,python实现。