Created
August 10, 2019 06:19
-
-
Save shharma-vipin/b8a0e993bfcd66e0c92ae6f4fa9e75de to your computer and use it in GitHub Desktop.
Postorder Travesal without Recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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