LeetCode:145 二叉树的后序遍历(用栈模拟递归,记录前一个输出的节点)
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
Deque<TreeNode> stack = new LinkedList<>();
TreeNode t = root;
TreeNode prev = null;
while(t!=null||!stack.isEmpty()){
if(t!=null){
stack.push(t);
t = t.left;
}
else{
t = stack.pop();
if(t.right==null||t.right==prev){
res.add(t.val);
prev = t;
t = null;
}
else{
stack.push(t);
t = t.right;
}
}
}
return res;
}
}