145. Binary Tree Postorder Traversal!
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> result = new LinkedList<>();
Deque<TreeNode> stack = new LinkedList<>();
if(root==null) return result;
stack.push(root);
while(stack.size()>0){
TreeNode current = stack.pop();
// this is the parent node, add it from the beginning
result.addFirst(current.val);
// add left first before right node
if(current.left!=null)stack.push(current.left);
if(current.right!=null)stack.push(current.right);
}
return result;
}
}
Last updated
Was this helpful?