class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> res = new LinkedList<>(); TreeNode prev = null; TreeNode p = root; Deque<TreeNode> stack = new LinkedList<>(); while(p!=null||!stack.isEmpty()){ if(p!=null){ while(p!=null){ stack.push(p); p = p.left; } } p = stack.pop(); if(p.right==null||p.right==prev){ res.add(p.val); prev = p; p = null; } else{ stack.push(p); p = p.right; } } return res; } }