# Binary Tree Postorder Traversal

Given a binary tree, return the_postorder_traversal of its nodes' values.

Example:

``````Input:
[1,null,2,3]

1
\
2
/
3

Output:
[3,2,1]
``````

Follow up:Recursive solution is trivial, could you do it iteratively?

## Solution

Recursive

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
recursivePreorderTraversal(root, result);
return result;
}
void recursivePreorderTraversal(TreeNode root, List<Integer> result) {
if (root != null) {
recursivePreorderTraversal(root.left, result);
recursivePreorderTraversal(root.right, result);
}
}
}
``````

LeetCode Official Solution

``````class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null) {
return output;
}

while (!stack.isEmpty()) {
TreeNode node = stack.pollLast();
if (node.left != null) {
}
if (node.right != null) {
}
}
return output;
}
}
``````

Iterative - Using Stack

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode p = root;
while(!stack.isEmpty() || p != null) {
if(p != null) {
stack.push(p);
result.addFirst(p.val);  // Reverse the process of preorder
p = p.right;             // Reverse the process of preorder
} else {
TreeNode node = stack.pop();
p = node.left;           // Reverse the process of preorder
}
}
return result;
}
}
``````