# Binary Tree Postorder Traversal – Leetcode Solution

In this post, we are going to solve the 145. Binary Tree Postorder Traversal problem of Leetcode. This problem 145. Binary Tree Postorder Traversal is a Leetcode easy level problem. Let’s see the code, 145. Binary Tree Postorder Traversal – Leetcode Solution.

Contents

## Problem

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

### Example 1 :

``````Input: root = [1,null,2,3]
Output: [3,2,1]``````

### Example 2 :

``````Input: root = []
Output: []``````

### Example 3 :

``````Input: root = [1]
Output: [1]``````

### Constraints

• The number of nodes in the tree is in the range `[0, 100]`.
• `-100 <= Node.val <= 100`

Now, let’s see the code of 145. Binary Tree Postorder Traversal – Leetcode Solution.

# Binary Tree Postorder Traversal – Leetcode Solution

### 145. Binary Tree Postorder Traversal – Solution in Java

```/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode() {}
*     TreeNode(int val) { this.val = val; }
*     TreeNode(int val, TreeNode left, TreeNode right) {
*         this.val = val;
*         this.left = left;
*         this.right = right;
*     }
* }
*/
class Solution {

public void postOrder(TreeNode root, List<Integer> ans){
if(root == null) return;

postOrder(root.left,ans);
postOrder(root.right,ans);
}
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
postOrder(root,ans);
return ans;
}
}```

### 145. Binary Tree Postorder Traversal – Solution in C++

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

### 145. Binary Tree Postorder Traversal– Solution in Python

```# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
def postorderTraversal(self, root):
res = []
self.dfs(root, res)
return res

def dfs(self, root, res):
if root:
self.dfs(root.left, res)
self.dfs(root.right, res)
res.append(root.val)
```

Note: This problem 145. Binary Tree Postorder Traversal is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.