Skip to content

Instantly share code, notes, and snippets.

@shharma-vipin
Created August 10, 2019 06:19
Show Gist options
  • Save shharma-vipin/b8a0e993bfcd66e0c92ae6f4fa9e75de to your computer and use it in GitHub Desktop.
Save shharma-vipin/b8a0e993bfcd66e0c92ae6f4fa9e75de to your computer and use it in GitHub Desktop.
Postorder Travesal without Recursion
public ArrayList<Integer> postorderTraversal(TreeNode A) {
Stack<TreeNode> s1 = new Stack<>();
Stack<TreeNode> s2 = new Stack<>();
if(A == null){
return null;
}
s1.push(A);
while(!s1.isEmpty()){
TreeNode temp = s1.pop();
s2.push(temp);
if(temp.left != null){
s1.push(temp.left);
}
if(temp.right != null){
s1.push(temp.right);
}
}
ArrayList<Integer> result = new ArrayList<>();
while(!s2.isEmpty()){
result.add(s2.pop().val);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment