Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active August 29, 2015 14:16
Show Gist options
  • Save dmnugent80/1b37e2cc342871d2a823 to your computer and use it in GitHub Desktop.
Save dmnugent80/1b37e2cc342871d2a823 to your computer and use it in GitHub Desktop.
Iterative Binary Tree Post-order Traversal
//Given a binary tree, return the postorder traversal of its nodes' values.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
TreeNode node = root;
Stack<TreeNode> stack = new Stack<TreeNode>();
LinkedList<Integer> retList = new LinkedList<Integer>();
while (true){
if (node != null){
retList.addFirst(node.val);
stack.push(node);
node = node.right;
}else{
if (stack.empty()){
return retList;
}
node = stack.pop();
node = node.left;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment