Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active August 23, 2017 01:50
Show Gist options
  • Select an option

  • Save cixuuz/1f6a9aee36b07cd889ee8ceb3bde7cd5 to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/1f6a9aee36b07cd889ee8ceb3bde7cd5 to your computer and use it in GitHub Desktop.
[145. Binary Tree Postorder Traversal] #leetcode
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> result = new LinkedList<Integer>();
TreeNode curNode = root;
Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
while ( !stack.isEmpty() || curNode != null ) {
if (curNode != null) {
stack.push(curNode);
result.addFirst(curNode.val);
curNode = curNode.right;
} else {
curNode = stack.pop().left;
}
}
return result;
}
}
class Solution1 {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> result = new LinkedList<Integer>();
if (root == null) return result;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while ( !stack.isEmpty() ) {
TreeNode curNode = stack.pop();
result.addFirst(curNode.val);
if (curNode.left != null) stack.push(curNode.left);
if (curNode.right != null) stack.push(curNode.right);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment