[leetcode] 145. Binary Tree Postorder Traversal 二叉树后序遍历

Given a binary tree, return the postorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [3,2,1].

解题思路:

递归版:

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

迭代版:

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ret;
        stack<TreeNode*> stk;
        TreeNode* curr = root;
        TreeNode* last = NULL;
        while(curr || !stk.empty())
        {
            while(curr)
            {
                 stk.push(curr);
                 curr = curr->left;
            }
            
            TreeNode* temp = stk.top();
            if(temp->right && last != temp->right )
                curr = temp->right;
            else{
                ret.push_back(temp->val);
                last = temp;
                 stk.pop();
             }
            
        }
        
        return ret;
    }
};

    原文作者:叶孤陈
    原文地址: https://www.jianshu.com/p/90fe433926cc
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞