Skip to content

Commit

Permalink
Create 0145-binary-tree-postorder-traversal
Browse files Browse the repository at this point in the history
Adding the Java solutions for the Postorder traversal
  • Loading branch information
Anukriti167 authored May 17, 2023
1 parent 9603026 commit 626f44a
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions java/0145-binary-tree-postorder-traversal
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
class Solution {
// Iterative
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
stack.add(root);
Stack<Boolean> visit = new Stack<>();
visit.add(false);

List<Integer> res = new ArrayList<>();

while(!stack.isEmpty()){
TreeNode curr=stack.pop();
boolean v = visit.pop();
if(curr != null){
if(v != false){
res.add(curr.val);
}else{
stack.add(curr);
visit.add(true);
stack.add(curr.right);
visit.add(false);
stack.add(curr.left);
visit.add(false);
}
}
}
return res;
}
}

class Solution {
// Recursive
public void postorder(TreeNode root, List<Integer> res){
if(root == null) return;

postorder(root.left, res);
postorder(root.right, res);
res.add(root.val);
}
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();

postorder(root, res);
return res;
}
}

0 comments on commit 626f44a

Please sign in to comment.