Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2484 from Anukriti167/patch-6
Browse files Browse the repository at this point in the history
Create 0145-binary-tree-postorder-traversal
  • Loading branch information
a93a authored May 17, 2023
2 parents 6840ef8 + 41fe878 commit ec95e5a
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions java/0145-binary-tree-postorder-traversal.java
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 ec95e5a

Please sign in to comment.