import java.util.ArrayList; import java.util.List; import java.util.Stack; public class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); if(root == null) return res; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode pre = null; stack.push(root); while(!stack.isEmpty()){ TreeNode curr = stack.peek(); if((curr.left == null && curr.right == null) || (pre != null && (pre == curr.left || pre == curr.right))){ res.add(curr.val); pre = curr; stack.pop(); }else{ if(curr.right != null) stack.push(curr.right); if(curr.left != null) stack.push(curr.left); } } return res; } }
后序遍历,左右根,左右节点都为空,添加根元素,当前节点不完空,不是左右节点,添加元素