---
# System prepended metadata

title: 145. Binary Tree Postorder Traversal
tags: [tree, Leetcode, python, c++, easy]

---

###### tags: `Leetcode` `easy` `tree` `python` `c++`

# 145. Binary Tree Postorder Traversal

## [題目出處:] https://leetcode.com/problems/binary-tree-postorder-traversal/

## 題目:
Given the root of a binary tree, return the postorder traversal of its nodes' values.

**Follow up: Recursive solution is trivial, could you do it iteratively?
**
## 解題想法:
##### 參考 [94. Binary Tree Inorder Traversal]https://hackmd.io/@Hungen/HJ5n2VI1j
##### 參考 [144. Binary Tree Preorder Traversal]https://hackmd.io/@Hungen/HJxk7DUyj

**Postorder: 左右(中)**
可以轉換成-> **(中)右左 再reverse**!!!

## Python ( Recursive & Iterative ):
``` python=
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
    def insertLeft(self,node):
        if self.left==None:
            self.left=TreeNode(node)
        else:
            self.left.insertLeft(node)
    def insertRight(self,node):
        if self.right==None:
            self.right=TreeNode(node)
        else:
            self.right.insertRight(node)
    def printTree(self):
        root=self
        stack=[root]
        res=[]
        while stack:
            root=stack.pop(0)
            res.append(root.val)
            if root.left:
                stack.append(root.left)
            if root.right:
                stack.append(root.right)
        print(res)

class SolutionRe():
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        self.res=[]
        self.dfs(root)
        return self.res
    def dfs(self,root):
        if not root:
            return 
        self.dfs(root.left)
        self.dfs(root.right)
        self.res.append(root.val)

class SolutionIt:
    #原本: 左右(中): 想法: 先求 (中)右左 再反轉
    def postorderTraversal(self,root):
        stack=[]
        res=[]
        while root or stack:
            if root:
                res.append(root.val)
                stack.append(root)
                root=root.right
            else:
                cur=stack.pop()
                root=cur.left
        return res[::-1]
                

root=TreeNode(1)
root.insertRight(2)
root.right.insertLeft(3)
print("Original:",end=" ")
root.printTree()

Recursive=SolutionRe()
re=Recursive.postorderTraversal(root)
print("Recursive: ",re)

Iterative=SolutionIt()
it=Iterative.postorderTraversal(root)
print("Iterative: ",it)
```

## C++ ( Recursive & Iterative ):
``` cpp=
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;

struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(): val(0), left(nullptr), right(nullptr){}
    TreeNode(int x): val(x), left(nullptr), right(nullptr){}
};

void InsertLeft(TreeNode* root, int data){
    TreeNode* tmp=root;
    if (tmp->left)
        InsertLeft(tmp->left,data);
    else{
        TreeNode* new_node=new TreeNode(data);
        tmp->left=new_node;
    }
}

void InsertRight(TreeNode* root, int data){
    TreeNode* tmp=root;
    if (tmp->right)
        InsertRight(tmp->right,data);
    else{
        TreeNode *new_node=new TreeNode(data);
        tmp->right=new_node;
    }
}

void PrintTree(TreeNode* root){
    TreeNode* tmp=root;
    vector<int> res;
    queue<TreeNode*> que;
    que.push(tmp);
    while(!que.empty()){
        TreeNode* cur=que.front(); que.pop();
        res.push_back(cur->val);
        if (cur->left)
            que.push(cur->left);
        if (cur->right)
            que.push(cur->right);
    }
    cout<<"Original Tree: ";
    for (int i=0; i<res.size(); i++){
        cout<<res[i]<<" ";
    }
    cout<<endl;
}

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

class SolutionIT{
public:
    vector<int> postorderTraversal(TreeNode* root){
        vector<int> res;
        stack<TreeNode*> tmp;
        // left right (mid)= reverse(mid right left)
        while (root || !tmp.empty()){
            if (root){
                res.push_back(root->val);
                tmp.push(root);
                root=root->right;
            }
            else{
                TreeNode* cur=tmp.top(); tmp.pop();
                root=cur->left;
            }
        }
        //<algorithm>
        reverse(res.begin(),res.end());
        return res;
    }
};

void PrintVector(vector<int>& nums){
    for (int i=0; i<nums.size(); i++){
        cout<<nums[i]<<" ";
    }
    cout<<endl;
}

int main(){
    TreeNode* root=new TreeNode(1);
    InsertRight(root,2);
    InsertLeft(root->right,3);
    PrintTree(root);

    SolutionRe Recursive;
    vector<int> re=Recursive.postorderTraversal(root);
    cout<<"Preorder: ";
    PrintVector(re);

    SolutionIT Iterative;
    vector<int> it=Iterative.postorderTraversal(root);
    cout<<"Preorder: ";
    PrintVector(it);

    return 0;
}

```

